lilydocs
HTTP APIWebSocketConsumer
HTTP2 min read

JSON, forms, and bodies

Choose the right extractor for the request body and preserve the single-consumer rule.

A body extractor owns the request body. Choosing JSON, a form, or a stream determines the parsing behavior, memory usage, and action contract.

Accept JSON#

For Json<T>, use a DTO with T: Deserialize. The content type must be application/json or application/*+json. The complete controller example includes the CreateUser DTO.

Create action snippet
#[post("/")]
async fn create(&self, Json(input): Json<CreateUser>)
    -> Result<Created<UserView>, HttpApiError>
{
    if input.name.trim().is_empty() {
        return Err(HttpApiError::ValidationError("name is required".into()));
    }
    Ok(Created::new("/users/42", UserView { id: 42, name: input.name }))
}
Example request
curl -i http://127.0.0.1:8080/users \
  -H 'Content-Type: application/json' \
  -d '{"name":"Ada"}'

Body types#

Extractor Expected data
Json<T> Bounded JSON
Form<T> application/x-www-form-urlencoded
MultipartForm<T> Typed text and file fields
RawBody A bounded byte buffer
BodyStream Chunk-by-chunk reading with next_chunk

For RawBody, an absent body yields an empty buffer; access it with as_bytes or into_inner. See file uploads for multipart details.

One body consumer#

Do not consume JSON together with multipart or a raw body in the same action. BodyStream takes terminal ownership: you cannot switch back to buffered reads afterward. BodyStream cannot be combined with &mut Request; the macro rejects it.

Even when raw request access is possible after a buffered extractor, it does not establish a second, independent body consumer. A custom body extractor must be the last typed parameter.

Size and time limits#

Parsing takes place within the transport's body limits. The default request body limit is 16 MiB. Set an appropriate limit for your application through transport configuration. Body reading is also included in the request's deadline, which starts at admission.

Sources for this page v0.1.0

This guide is based on the reviewed framework commit.

QUICK START
Documentation
Source code