Published on: 2022-04-12
Rust is gaining rapid adoption for building high-performance, safe backend services. One of its most popular web frameworks is Actix-web, known for speed and ergonomics.
Today, letβs build a simple REST API using Actix-web and explore its structure with a Mermaid class diagram.
βοΈ Prerequisites
- Rust version: 1.58+
- Actix-web version: 4.0
Install via Cargo:
cargo new rust_api
cd rust_api
cargo add actix-web
π§© Example: Todo API
Our API will:
- List todos (
GET /todos) - Create a new todo (
POST /todos)
π Project Structure
src/
main.rs
handlers.rs
models.rs
β¨ models.rs
Define a simple Todo struct:
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Todo {
pub id: u32,
pub title: String,
pub completed: bool,
}
β¨ handlers.rs
Create HTTP handlers:
use actix_web::{get, post, web, HttpResponse, Responder};
use crate::models::Todo;
#[get("/todos")]
async fn list_todos() -> impl Responder {
let todos = vec![
Todo { id: 1, title: "Learn Rust".into(), completed: false },
Todo { id: 2, title: "Build API".into(), completed: false },
];
HttpResponse::Ok().json(todos)
}
#[post("/todos")]
async fn create_todo(todo: web::Json<Todo>) -> impl Responder {
HttpResponse::Created().json(todo.0)
}
β¨ main.rs
Wire it all together:
use actix_web::{App, HttpServer};
mod handlers;
mod models;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(handlers::list_todos)
.service(handlers::create_todo)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
π Project Class Diagram
π₯ Running the API
Start the server:
cargo run
Test with curl:
curl http://127.0.0.1:8080/todos
π‘ Why Actix-web?
- Speed: Built on Actix actor framework, itβs among the fastest web frameworks in benchmarks.
- Type safety: Compile-time guarantees catch bugs early.
- Scalability: Great choice for high-concurrency microservices.
π§ TL;DR
- Rust + Actix-web = blazing fast, safe APIs
- Models, handlers, and routing remain cleanly separated
- Start with small projects like this before integrating with databases