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.

Quick Explain

  • ▸Actix-web uses the Actix actor framework and Rust's type system to ensure safety and concurrency.
  • ▸Supports asynchronous programming with Rust’s async/await syntax.
  • ▸Provides routing, middleware, extractors, and WebSocket support.
  • ▸Highly performant, capable of handling massive concurrent requests.
  • ▸Integrates seamlessly with Rust ecosystem libraries and crates.

Core Features

  • ▸Routing and URL handling
  • ▸Middleware for authentication, logging, and more
  • ▸Extractors for request data
  • ▸WebSocket and SSE support
  • ▸Integration with async Rust crates

Learning Path

  • ▸Learn Rust basics and ownership model
  • ▸Understand async/await in Rust
  • ▸Learn Actix-web routing, middleware, and handlers
  • ▸Work with extractors, services, and WebSockets
  • ▸Build small projects and increment complexity

Practical Examples

  • ▸Build a JSON REST API with CRUD endpoints
  • ▸Implement WebSocket-based chat server
  • ▸Create an async microservice with database integration
  • ▸Add JWT authentication middleware
  • ▸Integrate external Rust crates for caching or queues

Comparisons

  • ▸Actix-web vs Rocket: Actix faster, fully async; Rocket simpler but less performant
  • ▸Actix-web vs Warp: Actix higher performance; Warp more ergonomic for filter chaining
  • ▸Actix-web vs Node.js (Express): Actix memory-safe, compiled, extremely fast
  • ▸Actix-web vs Spring Boot: Actix for high concurrency; Spring Boot easier for JVM ecosystem
  • ▸Actix-web vs Django: Actix extremely fast; Django feature-rich and Python-based

Strengths

  • ▸Extremely high performance and low latency
  • ▸Memory-safe and thread-safe via Rust
  • ▸Supports async I/O natively
  • ▸Modular and extensible
  • ▸Suitable for high-concurrency workloads

Limitations

  • ▸Requires Rust knowledge
  • ▸Smaller ecosystem than Node.js or Python frameworks
  • ▸More verbose compared to some dynamic languages
  • ▸Compilation times can be long for large projects
  • ▸Limited built-in templating support (requires external crates)

When NOT to Use

  • ▸For simple static websites or small apps
  • ▸Teams without Rust knowledge
  • ▸Rapid prototyping where speed is not critical
  • ▸Projects requiring large ecosystems of libraries like Python/JS
  • ▸When compilation overhead is a concern

Cheat Sheet

  • ▸cargo new my_app - create new project
  • ▸cargo add actix-web - add Actix-web crate
  • ▸cargo run - run the application
  • ▸cargo test - run tests
  • ▸cargo build --release - build optimized binary

FAQ

  • ▸Is Actix-web open-source? -> Yes, MIT license.
  • ▸Does Actix-web support async? -> Yes, fully asynchronous.
  • ▸Can Actix-web be used for high-concurrency apps? -> Yes, designed for it.
  • ▸Does Actix-web support WebSockets? -> Yes, built-in support.
  • ▸How to debug Actix-web apps? -> Use logging, Actix test utilities, and Rust debugger.

30-Day Skill Plan

  • ▸Week 1: Install Rust and Actix-web, create hello-world
  • ▸Week 2: Implement CRUD REST API
  • ▸Week 3: Add async database integration
  • ▸Week 4: Implement middleware and WebSocket handlers
  • ▸Week 5: Optimize performance and deploy

Final Summary

  • ▸Actix-web is a Rust-based high-performance web framework.
  • ▸Supports async request handling, middleware, routing, and WebSockets.
  • ▸Memory-safe, thread-safe, and extremely fast.
  • ▸Suitable for APIs, microservices, and real-time applications.
  • ▸Integrates with Rust ecosystem crates for database, caching, and monitoring.

Project Structure

  • ▸src/main.rs - main application entry point
  • ▸src/routes/ - route handlers
  • ▸src/services/ - business logic and data access
  • ▸Cargo.toml - dependency management
  • ▸static/ - optional static assets

Monetization

  • ▸Actix-web is open-source (MIT license)
  • ▸Commercial consulting and support via Rust ecosystem
  • ▸Enterprise applications benefit from Rust performance
  • ▸Integration with monitoring and CI/CD tools
  • ▸High-performance services reduce operational cost

Productivity Tips

  • ▸Use Actix extractors for clean request handling
  • ▸Keep handlers async and non-blocking
  • ▸Modularize middleware and services
  • ▸Leverage Rust crates for common functionality
  • ▸Monitor performance regularly in production

Basic Concepts

  • ▸Handler - async function responding to requests
  • ▸Route - URL mapping to handler
  • ▸Middleware - pre/post-processing requests
  • ▸Extractor - retrieves data from requests
  • ▸App - defines routes and middleware configuration

Official Docs

  • ▸https://actix.rs/docs/
  • ▸Actix GitHub repository
  • ▸Community forums and Discord channels

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher