1. What is an API?
API stands for Application Programming Interface.
An API allows two different applications to communicate with each other.
For example:
- Your Rust application requests student information.
- A Laravel backend receives the request.
- Laravel fetches student data from the database.
- Laravel sends the data back as JSON.
- Your Rust application receives and displays the data.
Simple API Communication
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
3. Install Reqwest
Rust provides libraries for making HTTP requests.
One of the popular libraries is Reqwest.
We will use:
reqwest– To send HTTP requests.serde– To serialize and deserialize data.serde_json– To work with JSON.tokio– To run asynchronous Rust code.
Open your project terminal and execute:
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.
What is await?
The .await keyword waits for an asynchronous operation to complete without blocking the entire asynchronous runtime thread.
Example:
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:
Complete Code
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
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
Explanation
Postrepresents the expected JSON structure.Deserializeallows JSON data to be converted into a Rust structure.#[serde(rename = "userId")]maps the JSON propertyuserIdto the Rust fielduser_id.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.
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
Explanation
reqwest::Client::new()creates an HTTP client..post()defines the POST request..json(&student)converts the Rust structure into JSON and sends it as the request body..send()sends the request..error_for_status()returns an error for unsuccessful HTTP status codes..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:
- Authorization token
- Content-Type
- Accept
- API key
Example:
10. Send an Authorization Token
Many APIs require authentication.
A common method is sending a Bearer token.
The request includes an authorization header similar to:
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.
12. Make a PATCH Request
PATCH is generally used to update selected fields of an existing resource.
13. Make a DELETE Request
DELETE requests are used to delete resources.
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.
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:
And Laravel returns:
Create a Rust structure:
Fetch the records:
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:
- Send a GET request to retrieve a post.
- Retrieve all posts from JSONPlaceholder.
- Convert the API response into a Rust structure.
- Print only the post title.
- Send a POST request with a new student record.
- Send a custom Accept header.
- Send a Bearer authentication token to a test API.
- Create a reusable HTTP client.
- Connect Rust to your own Laravel API.
- Handle unsuccessful HTTP status codes.
18. Mini Project: Student API Reader
Create a Rust application that retrieves student records from a REST API.
Requirements
- Create a
Studentstructure. - Send a GET request to your Laravel API.
- Deserialize the JSON response into
Vec<Student>. - Display student ID, name, and course.
- Handle HTTP and JSON errors using
Result.