Building APIs with Rust
In this lesson, you will learn how to build REST APIs using Rust. Rust is increasingly popular for backend development because of its performance, safety, and reliability.
By the end of this lesson, you will understand how Rust is used to create real-world APIs that are fast, secure, and scalable.
What Is an API?
An API (Application Programming Interface) allows different software systems to communicate with each other.
In web development, APIs usually expose endpoints that clients can call using HTTP methods such as GET, POST, PUT, and DELETE.
Why Use Rust for APIs?
Rust is well-suited for backend APIs because it provides:
- High performance comparable to C/C++
- Memory safety without garbage collection
- Strong type system
- Excellent concurrency support
- Low resource usage
These advantages make Rust ideal for high-traffic and mission-critical systems.
Popular Rust Web Frameworks
Rust has several powerful web frameworks. The most commonly used ones are:
- Actix-web – Extremely fast and production ready
- Rocket – Simple and developer-friendly
- Axum – Modern, async-first framework
In this lesson, we will use Actix-web.
Creating a New API Project
Create a new Rust project using Cargo.
cargo new rust_api
cd rust_api
Adding Dependencies
Add Actix-web to your Cargo.toml.
[dependencies]
actix-web = "4"
Creating a Basic API Server
Below is a minimal API server with a single endpoint.
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello from Rust API!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(hello)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
This creates a server running on port 8080.
Running the API
Start the server using:
cargo run
Open your browser and visit:
http://localhost:8080
Handling JSON Responses
APIs often return JSON instead of plain text.
use actix_web::{get, web, HttpResponse};
#[get("/user")]
async fn user() -> HttpResponse {
HttpResponse::Ok().json(
serde_json::json!({
"id": 1,
"name": "Alice",
"role": "Admin"
})
)
}
This endpoint returns structured JSON data.
Handling Request Parameters
APIs often accept parameters from the URL.
use actix_web::{get, web, HttpResponse};
#[get("/user/{id}")]
async fn get_user(id: web::Path) -> HttpResponse {
HttpResponse::Ok().json(
serde_json::json!({
"user_id": id.into_inner()
})
)
}
Error Handling in APIs
Rust encourages explicit error handling. APIs should return meaningful HTTP status codes.
HttpResponse::NotFound().body("User not found")
Clear error responses improve API usability.
Where Rust APIs Are Used
- Microservices
- High-performance backends
- Cloud platforms
- Financial systems
- Blockchain services
📝 Practice Exercises
Exercise 1
Create an API endpoint that returns a list of users.
Exercise 2
Add a POST endpoint that accepts JSON input.
Exercise 3
Return a custom HTTP status code for errors.
✅ Practice Answers
Answer 1
Use HttpResponse::Ok().json() with a vector of users.
Answer 2
Use web::Json to parse incoming JSON payloads.
Answer 3
Use HttpResponse::BadRequest() or NotFound().
What’s Next?
In the next lesson, you will explore Rust web frameworks in more detail, including Actix and Rocket, and learn how to structure larger web applications.