Skip to main content

JSON Responses

Returning JSON data

Actix 4.9+ 5 min read

# JSON Responses

APIs primarily communicate via JSON. Actix Web makes it trivial to return JSON objects using Serde.

#The web::Json Wrapper

If you return a struct wrapped in web::Json, Actix Web automatically serializes it and sets the Content-Type to application/json.

code_blocksrust
use actix_web::{get, web, Responder};
use serde::Serialize;

#[derive(Serialize)]
struct User {
    id: u32,
    name: String,
}

#[get("/user")]
async fn get_user() -> impl Responder {
    let user = User { id: 1, name: "Alice".to_string() };
    web::Json(user)
}

#Using HttpResponse::json()

Alternatively, you can use the json() method on an HttpResponseBuilder to specify status codes alongside your JSON data.

code_blocksrust
use actix_web::HttpResponse;

async fn error_resp() -> HttpResponse {
    HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid Data" }))
}

Was this page helpful?

Reference Implementation

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

src/main.rs
1use actix_web::{get, web, App, HttpServer, Responder};
2use serde::Serialize;
3
4#[derive(Serialize)]
5struct Status {
6 healthy: bool,
7}
8
9#[get("/health")]
10async fn health_check() -> impl Responder {
11 web::Json(Status { healthy: true })
12}
13
14#[actix_web::main]
15async fn main() -> std::io::Result<()> {
16 HttpServer::new(|| App::new().service(health_check))
17 .bind(("127.0.0.1", 8080))?
18 .run()
19 .await
20}
Was this page helpful?