↓Skip to main content
Building a REST API with Rust using Actix-web
  1. Blog Posts/

πŸ¦€ Building a REST API with Rust using Actix-web

2 min readΒ·
rust api actix-web

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