actix-web Documentation

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

24,861 stars Rust Rust 13 files ยท ~3,954 tokens #actix#actix-web#async#rust#web#web-development#websockets
RAW Doc

Technical Documentation: actix/actix-web

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`actix-files/README.md`)

`actix-files`




Static file serving for Actix Web.

Provides a non-blocking service for serving static files from disk.

Examples

rust
use actix_web::App;
use actix_files::Files;

let app = App::new()
    .service(Files::new("/static", ".").prefer_utf8(true));

Sponsors


Overview (`actix-http-test/README.md`)

`actix-http-test`




Various helpers for Actix applications to use during testing.

Sponsors


Overview (`actix-http/README.md`)

`actix-http`

HTTP types and services for the Actix ecosystem.




Examples

rust
use std::{env, io};

use actix_http::{HttpService, Response};
use actix_server::Server;
use futures_util::future;
use http::header::HeaderValue;
use tracing::info;

#[actix_rt::main]
async fn main() -> io::Result<()> {
    env::set_var("RUST_LOG", "hello_world=info");
    env_logger::init();

    Server::build()
        .bind("hello-world", "127.0.0.1:8080", || {
            HttpService::build()
                .client_timeout(1000)
                .client_disconnect(1000)
                .finish(|_req| {
                    info!("{:?}", _req);
                    let mut res = Response::Ok();
                    res.header("x-head", HeaderValue::from_static("dummy value!"));
                    future::ok::<_, ()>(res.body("Hello world!"))
                })
                .tcp()
        })?
        .run()
        .await
}

Sponsors


Overview (`actix-multipart-derive/README.md`)

`actix-multipart-derive`

The derive macro implementation for actix-multipart-derive.




Sponsors


Overview (`actix-multipart/README.md`)

`actix-multipart`




Multipart request & form support for Actix Web.

The [Multipart] extractor aims to support all kinds of multipart/* requests, including multipart/form-data, multipart/related and multipart/mixed. This is a lower-level extractor which supports reading multipart fields, in the order they are sent by the client.

Due to additional requirements for multipart/form-data requests, the higher level MultipartForm extractor and derive macro only supports this media type.

Examples

rust
use actix_multipart::form::{
    json::Json as MpJson, tempfile::TempFile, MultipartForm, MultipartFormConfig,
};
use actix_web::{middleware::Logger, post, App, HttpServer, Responder};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Metadata {
    name: String,
}

#[derive(Debug, MultipartForm)]
struct UploadForm {
    // Note: the form is also subject to the global limits configured using `MultipartFormConfig`.
    #[multipart(limit = "100MB")]
    file: TempFile,
    json: MpJson<Metadata>,
}

#[post("/videos")]
async fn post_video(MultipartForm(form): MultipartForm<UploadForm>) -> impl Responder {
    format!(
        "Uploaded file {}, with size: {}\ntemporary file ({}) was deleted\n",
        form.json.name,
        form.file.size,
        form.file.file.path().display(),
    )
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

    HttpServer::new(move || {
        App::new()
            .service(post_video)
            .wrap(Logger::default())
            // Also increase the global total limit to 100MiB.
            .app_data(MultipartFormConfig::default().total_limit(100 * 1024 * 1024))
    })
    .workers(2)
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

cURL request:

sh
curl -v --request POST \
  --url http://localhost:8080/videos \
  -F 'json={"name": "Cargo.lock"};type=application/json' \
  -F file=@./Cargo.lock

More available in the examples repo →

Sponsors


Overview (`actix-router/README.md`)

`actix-router`




Resource path matching and router.

Sponsors


Overview (`actix-test/README.md`)

`actix-test`




Integration testing tools for Actix Web applications.

The main integration testing tool is [TestServer]. It spawns a real HTTP server on an unused port and provides methods that use a real HTTP client. Therefore, it is much closer to real-world cases than using init_service, which skips HTTP encoding and decoding.

Examples

rust
use actix_web::{get, web, test, App, HttpResponse, Error, Responder};

#[get("/")]
async fn my_handler() -> Result<impl Responder, Error> {
    Ok(HttpResponse::Ok())
}

#[actix_rt::test]
async fn test_example() {
    let srv = actix_test::start(||
        App::new().service(my_handler)
    );

    let req = srv.get("/");
    let res = req.send().await.unwrap();

    assert!(res.status().is_success());
}

Sponsors


Overview (`actix-web-actors/README.md`)

`actix-web-actors`

Actix actors support for Actix Web.

This crate is deprecated. Migrate to actix-ws.



Sponsors


Overview (`actix-web-codegen/README.md`)

`actix-web-codegen`

Routing and runtime macros for Actix Web.




Compile Testing

Uses the trybuild crate. All compile fail tests should include a stderr file generated by trybuild. See the workflow section of the trybuild docs for info on how to do this.

Sponsors


Overview (`actix-web/README.md`)

Features

  • Supports HTTP/1.x and HTTP/2
  • Streaming and pipelining
  • Powerful request routing with optional macros
  • Full Tokio compatibility
  • Keep-alive and slow requests handling
  • Client/server WebSockets support
  • Transparent content compression/decompression (br, gzip, deflate, zstd)
  • Multipart streams
  • Static assets
  • SSL support using OpenSSL or Rustls
  • Middlewares (Logger, Session, CORS, etc)
  • Integrates with the awc HTTP client
  • Runs on stable Rust 1.88+

Experimental features

To enable faster release iterations, we mark some features as experimental. These features are prefixed with experimental and a breaking change may happen at any release. Please use them in a production environment at your own risk.

Documentation

Example

Dependencies:

toml
[dependencies]
actix-web = "4"

Code:

rust
use actix_web::{get, web, App, HttpServer, Responder};

#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
    format!("Hello {name}!")
}

#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(greet)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

More Examples

You may consider checking out this directory for more examples.

Benchmarks

One of the fastest web frameworks available according to the TechEmpower Framework Benchmark.

License

This project is licensed under either of the following licenses, at your option:

Code of Conduct

Contribution to the actix/actix-web repo is organized under the terms of the Contributor Covenant. The Actix team promises to intervene to uphold that code of conduct.

Sponsors


Overview (`awc/README.md`)

`awc` (Actix Web Client)

Async HTTP and WebSocket client library.



Examples

Example project using TLS-enabled client โ†’

Basic usage:

rust
use actix_rt::System;
use awc::Client;

fn main() {
    System::new().block_on(async {
        let client = Client::default();

        let res = client
            .get("http://www.rust-lang.org")    // <- Create request builder
            .insert_header(("User-Agent", "Actix-web"))
            .send()                             // <- Send http request
            .await;

        println!("Response: {:?}", res);        // <- server http response
    });
}

Sponsors


Overview (`actix-web/examples/README.md`)

Actix Web Examples

This folder contain just a few standalone code samples. There is a much larger registry of example projects in the examples repo.


Overview (`docs/graphs/README.md`)

Actix Ecosystem Dependency Graphs

See rendered versions of these dot graphs on the wiki.

Rendering

Dot graphs were rendered using the dot command from GraphViz:

sh
for f in $(ls docs/graphs/*.dot | xargs); do dot $f -Tpng -o${f:r}.png; done

--- METRICS ---