1. Home
  2. /
  3. Actix-web
  4. /
  5. Actix Web Simple REST API

Actix Web Simple REST API - Actix-web Typing CST Test

Loading…

Actix Web Simple REST API — Actix-web Code

Demonstrates a simple Actix Web application with routes for listing and adding Todo items.

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;

#[derive(Serialize, Deserialize, Clone)]
struct Todo {
    id: u32,
    title: String,
    completed: bool,
}

struct AppState {
    todos: Mutex<Vec<Todo>>,
}

async fn get_todos(data: web::Data<AppState>) -> impl Responder {
    let todos = data.todos.lock().unwrap();
    HttpResponse::Ok().json(&*todos)
}

async fn add_todo(todo: web::Json<Todo>, data: web::Data<AppState>) -> impl Responder {
    let mut todos = data.todos.lock().unwrap();
    todos.push(todo.into_inner());
    HttpResponse::Created().finish()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let app_state = web::Data::new(AppState { todos: Mutex::new(Vec::new()) });

    HttpServer::new(move || {
        App::new()
            .app_data(app_state.clone())
            .route("/todos", web::get().to(get_todos))
            .route("/todos", web::post().to(add_todo))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Actix-web Language Guide

Actix-web is a powerful, pragmatic, and extremely fast web framework for Rust, designed for building web applications, APIs, and microservices with high performance and safety.

Primary Use Cases

  • ▸High-performance REST APIs
  • ▸Microservices with async handling
  • ▸Web applications with low-latency requirements
  • ▸Real-time communication via WebSockets
  • ▸IoT backends and event-driven systems

Notable Features

  • ▸Asynchronous and concurrent request handling
  • ▸Rust’s type system ensures memory safety
  • ▸Routing, middleware, and extractors built-in
  • ▸WebSocket support for real-time communication
  • ▸Extensible via Rust crates ecosystem

Origin & Creator

Created by Nikolay Kim in 2017 and maintained by the Actix community.

Industrial Note

Actix-web is favored in performance-critical applications such as APIs, microservices, IoT backends, and real-time systems where Rust’s safety and speed are advantageous.

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher