Skip to main content

JSON

Parsing JSON request bodies

Actix 4.9+ 6 min read

# JSON Extractor

When building APIs, receiving JSON data is a primary requirement. Actix Web uses the web::Json extractor to seamlessly parse incoming JSON payloads into Rust structs.

#Basic Extraction

Simply define a struct that implements Deserialize, and wrap it in web::Json in your handler arguments.

code_blocksrust
use actix_web::{post, web, HttpResponse};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}

#[post("/users")]
async fn create_user(info: web::Json<CreateUser>) -> HttpResponse {
    HttpResponse::Ok().body(format!("Welcome {}!", info.username))
}

#Payload Configuration

By default, the JSON extractor limits the payload size to prevent Denial of Service (DoS) attacks. You can adjust this limit and customize the error response.

code_blocksrust
use actix_web::{web, App};

App::new().app_data(web::JsonConfig::default().limit(4096))

Was this page helpful?

Reference Implementation

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

src/main.rs
1use actix_web::{post, web, App, HttpServer, Responder, HttpResponse};
2use serde::Deserialize;
3
4#[derive(Deserialize)]
5struct Item {
6 name: String,
7 count: u32,
8}
9
10#[post("/add")]
11async fn add_item(item: web::Json<Item>) -> impl Responder {
12 HttpResponse::Ok().body(format!("Added {} x {}", item.count, item.name))
13}
14
15#[actix_web::main]
16async fn main() -> std::io::Result<()> {
17 HttpServer::new(|| App::new().service(add_item))
18 .bind(("127.0.0.1", 8080))?
19 .run()
20 .await
21}
Was this page helpful?