Skip to main content

Status Codes

Customizing HTTP status codes

Actix 4.9+ 4 min read

# Status Codes

By default, successful handlers return a 200 OK. However, robust APIs use a variety of status codes (201 Created, 404 Not Found, 400 Bad Request) to communicate accurately.

#HttpResponse Builders

The HttpResponse struct provides static methods for common status codes.

code_blocksrust
use actix_web::HttpResponse;

async fn created() -> HttpResponse {
    HttpResponse::Created().body("Resource created") // 201
}

async fn forbidden() -> HttpResponse {
    HttpResponse::Forbidden().body("Access denied") // 403
}

#Custom Status Codes

If you need a specific code not provided by a convenience method, use build() with a StatusCode enum.

code_blocksrust
use actix_web::{http::StatusCode, HttpResponse};

async fn custom_status() -> HttpResponse {
    HttpResponse::build(StatusCode::IM_A_TEAPOT)
        .body("Short and stout")
}

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, App, HttpServer, HttpResponse, Responder};
2
3#[get("/not-found")]
4async fn not_found() -> impl Responder {
5 HttpResponse::NotFound().body("Page not found")
6}
7
8#[actix_web::main]
9async fn main() -> std::io::Result<()> {
10 HttpServer::new(|| App::new().service(not_found))
11 .bind(("127.0.0.1", 8080))?
12 .run()
13 .await
14}
Was this page helpful?