Rust
December 2, 2026 8 min read

Working with REST APIs in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What is an API?

API stands for Application Programming Interface.

An API allows two different applications to communicate with each other.

For example:

  1. Your Rust application requests student information.
  2. A Laravel backend receives the request.
  3. Laravel fetches student data from the database.
  4. Laravel sends the data back as JSON.
  5. Your Rust application receives and displays the data.

Simple API Communication

Rust Application
|
| HTTP Request
v
Laravel API
|
v
Database
|
v
Laravel API
|
| JSON Response
v
Rust Application

2. What is REST API?

REST stands for Representational State Transfer.

A REST API is a common way for applications to communicate over HTTP.

REST APIs generally use these HTTP methods:


Method

Purpose

Example

GET

Retrieve data

Get all students

POST

Create data

Add a student

PUT

Update complete data

Update student details

PATCH

Update part of data

Update student email

DELETE

Delete data

Delete a student

Example API Endpoints

GET https://example.com/api/students
GET https://example.com/api/students/1
POST https://example.com/api/students
PUT https://example.com/api/students/1
PATCH https://example.com/api/students/1
DELETE https://example.com/api/students/1

3. Install Reqwest

Rust provides libraries for making HTTP requests.

One of the popular libraries is Reqwest.

We will use:

  1. reqwest – To send HTTP requests.
  2. serde – To serialize and deserialize data.
  3. serde_json – To work with JSON.
  4. tokio – To run asynchronous Rust code.

Open your project terminal and execute:

cargo add reqwest --features json
cargo add serde --features derive
cargo add serde_json
cargo add tokio --features macros,rt-multi-thread

These commands add the required dependencies to Cargo.toml.

4. Understanding Async and Await

HTTP requests may take time because they depend on network communication.

Rust supports asynchronous programming using async and await.

What is async?

The async keyword defines an asynchronous function.

async fn get_data() {
println!("Fetching data...");
}

What is await?

The .await keyword waits for an asynchronous operation to complete without blocking the entire asynchronous runtime thread.

Example:

async fn get_data() {
let result = fetch_data().await;
}

We will use async and .await when working with Reqwest.

5. Make Your First GET Request

GET requests are used to retrieve information from a server.

For practice, we will use this public test API:

https://jsonplaceholder.typicode.com/posts/1

Complete Code

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let response = reqwest::get(
"https://jsonplaceholder.typicode.com/posts/1"
).await?;

let body = response.text().await?;

println!("{}", body);

Ok(())
}

Explanation

1. #[tokio::main]

Starts the Tokio asynchronous runtime and allows us to use .await inside main.

2. reqwest::get()

Sends an HTTP GET request.

3. .await

Waits for the HTTP request to complete.

4. response.text()

Reads the response body as text.

5. ?

Returns an error if the operation fails.

Expected Output

{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati",
"body": "quia et suscipit..."
}

The complete response contains additional text.

6. Convert API JSON into a Rust Structure

Instead of receiving JSON as a simple string, we can deserialize it directly into a Rust structure.

This is useful when building real applications.

Complete Code

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Post {
#[serde(rename = "userId")]
user_id: u32,
id: u32,
title: String,
body: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let response = reqwest::get(
"https://jsonplaceholder.typicode.com/posts/1"
).await?;

let post: Post = response.json().await?;

println!("Post ID: {}", post.id);
println!("User ID: {}", post.user_id);
println!("Title: {}", post.title);
println!("Body: {}", post.body);

Ok(())
}

Explanation

  1. Post represents the expected JSON structure.
  2. Deserialize allows JSON data to be converted into a Rust structure.
  3. #[serde(rename = "userId")] maps the JSON property userId to the Rust field user_id.
  4. response.json() reads the response and converts it into the specified Rust type.

7. Check HTTP Response Status

An HTTP request can complete successfully at the network level while the server returns an error status such as 404 or 500.

Use status() to inspect the HTTP response status.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let response = reqwest::get(
"https://jsonplaceholder.typicode.com/posts/1"
).await?;

println!("Status: {}", response.status());

if response.status().is_success() {
println!("Request successful!");
} else {
println!("Request failed!");
}

Ok(())
}

Common HTTP status codes:


Code

Meaning

200

OK

201

Created

400

Bad Request

401

Unauthorized

403

Forbidden

404

Not Found

422

Unprocessable Content

500

Internal Server Error

Important: response.json() does not automatically treat every non-2xx HTTP status as an error. Check the status or use error_for_status() when appropriate.

8. Make a POST Request

POST requests are commonly used to send new information to a server.

For example, sending student information to a Laravel API.

Complete Code

use serde::Serialize;

#[derive(Serialize)]
struct Student {
name: String,
course: String,
fees: u32,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let student = Student {
name: String::from("Rahul"),
course: String::from("Rust"),
fees: 5000,
};

let client = reqwest::Client::new();

let response = client
.post("https://jsonplaceholder.typicode.com/posts")
.json(&student)
.send()
.await?
.error_for_status()?;

let result = response.text().await?;

println!("{}", result);

Ok(())
}

Explanation

  1. reqwest::Client::new() creates an HTTP client.
  2. .post() defines the POST request.
  3. .json(&student) converts the Rust structure into JSON and sends it as the request body.
  4. .send() sends the request.
  5. .error_for_status() returns an error for unsuccessful HTTP status codes.
  6. .text() reads the response.

The JSONPlaceholder API is a testing service. It simulates creating a post; it does not permanently save your student record.

9. Send Custom Headers

Some APIs require additional information in HTTP headers.

For example:

  1. Authorization token
  2. Content-Type
  3. Accept
  4. API key

Example:

use reqwest::header;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let client = reqwest::Client::new();

let response = client
.get("https://jsonplaceholder.typicode.com/posts/1")
.header(header::ACCEPT, "application/json")
.send()
.await?
.error_for_status()?;

println!("{}", response.text().await?);

Ok(())
}

10. Send an Authorization Token

Many APIs require authentication.

A common method is sending a Bearer token.

let token = "YOUR_API_TOKEN";

let response = client
.get("https://example.com/api/students")
.bearer_auth(token)
.send()
.await?
.error_for_status()?;

The request includes an authorization header similar to:

Authorization: Bearer YOUR_API_TOKEN

Never hardcode real secret tokens in source code that you share or publish. Use environment variables or a secure secrets manager.

11. Make a PUT Request

PUT is generally used to replace an existing resource.

use serde::Serialize;

#[derive(Serialize)]
struct Student {
name: String,
course: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let student = Student {
name: String::from("Rahul Singh"),
course: String::from("Advanced Rust"),
};

let client = reqwest::Client::new();

let response = client
.put("https://example.com/api/students/1")
.json(&student)
.send()
.await?
.error_for_status()?;

println!("Status: {}", response.status());

Ok(())
}

12. Make a PATCH Request

PATCH is generally used to update selected fields of an existing resource.

use serde::Serialize;

#[derive(Serialize)]
struct StudentUpdate {
course: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let update = StudentUpdate {
course: String::from("Rust Programming"),
};

let client = reqwest::Client::new();

let response = client
.patch("https://example.com/api/students/1")
.json(&update)
.send()
.await?
.error_for_status()?;

println!("Updated: {}", response.status());

Ok(())
}

13. Make a DELETE Request

DELETE requests are used to delete resources.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let client = reqwest::Client::new();

let response = client
.delete("https://example.com/api/students/1")
.send()
.await?
.error_for_status()?;

println!("Delete status: {}", response.status());

Ok(())
}

This example uses a placeholder URL. Use a real API endpoint when testing against your own backend.

14. Use a Reusable HTTP Client

When making multiple API requests, it is better to create one reqwest::Client and reuse it.

let client = reqwest::Client::new();

let response1 = client
.get("https://example.com/api/students")
.send()
.await?;

let response2 = client
.get("https://example.com/api/courses")
.send()
.await?;

A reusable client can manage connection pooling and shared client configuration.

15. Connect Rust with a Laravel API

Suppose your Laravel application provides this endpoint:

GET https://capscomtechnology.com/api/students

And Laravel returns:

[
{
"id": 1,
"name": "Rahul",
"course": "ADCA"
},
{
"id": 2,
"name": "Amit",
"course": "Python"
}
]

Create a Rust structure:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Student {
id: u32,
name: String,
course: String,
}

Fetch the records:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

let client = reqwest::Client::new();

let response = client
.get("https://capscomtechnology.com/api/students")
.send()
.await?
.error_for_status()?;

let students: Vec<Student> = response.json().await?;

for student in students {
println!(
"{} - {} - {}",
student.id,
student.name,
student.course
);
}

Ok(())
}

This example assumes the Laravel endpoint is publicly accessible and returns the JSON structure shown above. If your API requires authentication, send the appropriate token.

16. Important Concepts


Concept

Purpose

API

Allows applications to communicate

REST

Common architectural style for web APIs

HTTP

Protocol used for web communication

GET

Retrieve data

POST

Create data

PUT

Replace data

PATCH

Partially update data

DELETE

Delete data

Reqwest

Rust HTTP client library

Tokio

Asynchronous runtime

Async

Defines asynchronous functions

Await

Waits for an asynchronous operation

Status Code

Indicates the result of an HTTP request

Headers

Carry additional request or response information

17. Practice Exercises

Try these exercises:

  1. Send a GET request to retrieve a post.
  2. Retrieve all posts from JSONPlaceholder.
  3. Convert the API response into a Rust structure.
  4. Print only the post title.
  5. Send a POST request with a new student record.
  6. Send a custom Accept header.
  7. Send a Bearer authentication token to a test API.
  8. Create a reusable HTTP client.
  9. Connect Rust to your own Laravel API.
  10. Handle unsuccessful HTTP status codes.

18. Mini Project: Student API Reader

Create a Rust application that retrieves student records from a REST API.

Requirements

  1. Create a Student structure.
  2. Send a GET request to your Laravel API.
  3. Deserialize the JSON response into Vec<Student>.
  4. Display student ID, name, and course.
  5. Handle HTTP and JSON errors using Result.

Expected Output

Student Records

ID: 1
Name: Rahul
Course: ADCA

ID: 2
Name: Amit
Course: Python