Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Web Application Extractors and Responders

Extractors and responders handle request parsing and response building, so your handlers can focus on application logic. Extractors provide a handler’s arguments. Responders turn its return value into an HTTP response.

Extractors

Extractors turn request data into typed handler arguments. Each argument type must implement FromRequest. A handler can take up to 16 extractor arguments.

Before calling a handler registered with Route::to(), ntex creates its arguments from the request. It extracts each argument in the order it appears in the function signature.

The built-in extractors cover common request data. The rejection statuses below assume the default error domain; an application can choose different responses in Error Handling.

ExtractorReadsRejection with the default domain
HttpRequestA cheap clone of the request handleExtraction cannot fail
Path<T>Dynamic path segments404 if deserialization fails
Query<T>URL query parameters400 if deserialization fails
Json<T>A JSON request body400 for content-type or parsing errors; 413 for size limit
Form<T>A URL-encoded request body400 for invalid input; 413 for overflow; 411 for malformed length
PayloadThe streaming request bodyExtraction cannot fail; reading the stream can
BytesThe complete request body as bytes413 for overflow; 400 for other payload errors
StringThe complete request body as decoded textAs for Bytes, plus 400 for invalid charset or text
Option<T>Some(value), or None if T failsDoes not reject the request
Result<T, T::Error>The value, or the error produced by TLeaves rejection to the handler
(A, B, ...)Several extractors combined into one argumentUses the failing extractor’s response

For example, this handler reads a user ID from the path and an optional flag from the query string:

use ntex::web::{self, App};

#[derive(serde::Deserialize)]
struct Options {
    details: Option<bool>,
}

async fn user(
    user_id: web::types::Path<u32>,
    options: web::types::Query<Options>,
) -> String {
    format!(
        "User {}, details: {}",
        user_id.into_inner(),
        options.details.unwrap_or(false),
    )
}

App::default().route(
    "/users/{user_id}",
    web::get().to(user),
);

If any extractor fails, ntex skips the handler and turns the error into a response through WebResponseError.

Path<T> uses serde to deserialize captured path segments. Query<T> also uses serde, but query strings have a different shape:

  • A path tuple reads captured segments by position.
  • A path struct reads them by route variable name.
  • A query string contains key=value pairs. Use a struct or map rather than a tuple.

ntex percent-decodes path values after splitting the URL into segments. An encoded slash such as %2F can therefore appear inside one extracted value. Do not treat path values as safe file-system paths; they are request input.

Choosing Handler Arguments

Keep the public shape of the endpoint visible in its signature. A route such as /users/{user_id} usually takes a Path<u32>; pagination or filtering belongs in a Query<SearchOptions>. A JSON document belongs in Json<T>. You can combine these with HttpRequest when you also need a header, the request method, or other metadata. Reading the request handle does not consume the body.

Deserialization checks representation, not your business rules. A u32 path rejects a name such as alice, but it accepts 0 even if your database never uses zero as an ID. A Json<NewUser> checks the document’s shape, not whether the username is available. Perform those checks in the handler or a reusable validation function and return an application error when they fail.

Use Option on fields to make individual fields optional. For example, details: Option<bool> allows the query to omit details, but still rejects details=perhaps. This differs from wrapping the entire extractor in Option<Query<Options>>, which also ignores malformed input.

Application state is not another entry in the extractor list: this version has no web::types::State<T> extractor. Register a state-aware handler with to_with_state() instead. Its first argument borrows application state; its second receives request-local state, which is () without a state-changing filter. Extractor arguments follow those two. See Application State for a complete setup and sharing patterns.

Request Bodies

Choose a body extractor for the format your handler expects. All extractors share a request’s single body stream, so a handler should normally have only one body extractor.

The following extractors consume the stream and buffer it in memory. Each has a default size limit:

ExtractorDefault limit
Json<T>32 KiB
Form<T>16 KiB
Bytes and String256 KiB

Json<T> deserializes values with serde and accepts JSON media types, including those with a +json suffix. Form<T> also uses serde and requires application/x-www-form-urlencoded. The query extractor, Query<T>, uses serde too.

String decodes the body according to the request charset. Bytes returns bytes without text decoding. Both can decode compressed content, as described under incremental uploads.

Each body format has its own configuration:

  • JsonConfig changes the JSON size limit. JsonConfig::content_type() replaces the default */json and */*+json check with your predicate. Include JSON types in that predicate if you want to keep accepting them.
  • FormConfig changes only the form size limit.
  • PayloadConfig changes the limit for Bytes and String. It can also require a content type. Without that setting, both extractors accept any content type.

Store extractor configuration in WebAppConfig with set_value(). Install that configuration with App::with_config():

use ntex::web::{self, App, WebAppConfig};

fn main() {
    let config = WebAppConfig::new()
        .set_value(web::types::JsonConfig::default().limit(4096))
        .set_value(web::types::FormConfig::default().limit(8192))
        .set_value(web::types::PayloadConfig::new(64 * 1024));

    let app = App::default()
        .with_config(config)
        .route("/", web::post().to(async |body: String| body));
}

Values stored with set_value() must be Send + Sync. Extractors read their configuration only from WebAppConfig. They ignore a JsonConfig placed in application state, such as AppState<JsonConfig>.

Without a call to with_config(), the application uses the WebAppConfig from the connection’s shared configuration. Extractors use their defaults when that store has no configuration of the right type.

Use Payload to process the body incrementally without buffering it all in memory. It takes ownership of the remaining body stream and does not apply PayloadConfig. Your handler decides how much data to read and how to handle it.

Reading an Upload Incrementally

For an upload you only need to count, forward, or process in chunks, buffering the entire body is unnecessary. This handler counts bytes while enforcing its own one-MiB limit:

use ntex::web::{self, App, InternalError, types::Payload};

async fn upload(
    mut body: Payload,
) -> Result<String, InternalError<&'static str>> {
    const LIMIT: usize = 1024 * 1024;
    let mut total = 0;
    while let Some(chunk) = body.recv().await {
        let chunk = chunk
            .map_err(|_| web::error::ErrorBadRequest("Cannot read upload"))?;
        if chunk.len() > LIMIT - total {
            return Err(web::error::ErrorPayloadTooLarge(
                "Upload exceeds one MiB",
            ));
        }
        total += chunk.len();
    }
    Ok(format!("Received {total} bytes"))
}

fn main() {
    let app = App::default().route("/upload", web::post().to(upload));
}

A successful extraction only hands over the stream. The handler can still fail while reading it, which is why this example returns Result. Do not trust Content-Length as the only size check: count the actual chunks too. A real upload handler can write each chunk to storage rather than keeping it. It should also clean up partial work if reading fails or the request is cancelled.

With the compress feature, Bytes, String, Json<T>, and Form<T> decode Content-Encoding before processing the body. Payload exposes the encoded bytes instead. For compressed uploads, wrap the raw stream with ntex::http::encoding::Decoder::from_headers() if you need decoded data, and apply your limit to the decoded chunks. The example above counts the bytes it actually receives, not a decompressed size.

Request and Response Streaming covers backpressure, slow clients, records split across chunks, compressed uploads, and trailers.

Optional Extractors

Wrap an extractor in Option<T> when your handler should run even if that input is invalid. Successful extraction produces Some(value). A failure produces None and is also logged:

use ntex::web::{self, App};

#[derive(serde::Deserialize)]
struct Search {
    query: String,
}

async fn search(params: Option<web::types::Query<Search>>) -> String {
    match params {
        Some(params) => format!("Searching for {}", params.query),
        None => "No search query".to_owned(),
    }
}

App::default().route("/search", web::get().to(search));

If the handler needs the actual error, use Result<T, T::Error> instead. Both forms allow the handler to run when extraction fails.

None covers every extraction error, including input that is present but invalid. It does not mean the input was missing. Use Option<T> only for input you are willing to ignore when it is invalid.

With Option<Json<T>>, malformed JSON reaches the handler as None, rather than producing the 400 response from Json<T>. A body over the JsonConfig limit also becomes None, rather than a 413 response.

To make input optional while rejecting invalid input, extract Result<T, T::Error> and decide which errors mean “missing”. For Json<T>, JsonPayloadError::ContentType means the request has no JSON content type, which is usually the case when it sends no body. Return every other error to keep the response that Json<T> would produce:

use ntex::web::{self, App, error::JsonPayloadError, types::Json};

#[derive(serde::Deserialize)]
struct Settings {
    theme: String,
}

async fn update(
    body: Result<Json<Settings>, JsonPayloadError>,
) -> Result<String, JsonPayloadError> {
    let settings = match body {
        Ok(Json(settings)) => Some(settings),
        Err(JsonPayloadError::ContentType) => None,
        Err(e) => return Err(e), // malformed: 400, too large: 413
    };
    Ok(match settings {
        Some(s) => format!("Theme set to {}", s.theme),
        None => "Settings unchanged".to_owned(),
    })
}

App::default().route("/settings", web::post().to(update));

These wrappers do not rewind the request body. How much of the stream a failed extractor consumes depends on where it fails. For example, Json<T> rejects an unsupported content type before reading anything. If deserialization fails, it has already read the body.

A later extractor may see the whole body, part of it, or nothing. (Option<Json<T>>, Bytes) is therefore not a reliable “JSON or raw body” fallback. Keep a wrapped body extractor as the handler’s only body extractor.

For a fallback, read the body once as Bytes and parse the bytes you kept:

use ntex::http::HttpMessage;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpRequest};

async fn ingest(req: HttpRequest, body: Bytes) -> String {
    if req.content_type() == "application/json"
        && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&body)
    {
        return format!("JSON: {value}");
    }
    format!("raw body: {} bytes", body.len())
}

App::default().route("/ingest", web::post().to(ingest));

This buffers the body once, under the PayloadConfig limit of 256 KiB by default. The JsonConfig limit does not apply. Unless PayloadConfig requires a content type, Bytes accepts any type, so the handler checks it itself.

Custom Extractors

Implement FromRequest to turn application-specific request data into a handler argument. Your extractor receives the application state, the HTTP request, and mutable access to the request body.

The body argument is the raw http::Payload stream. Use it directly in a custom extractor. The Payload extractor in web::types is a separate type that wraps this stream for use as a handler argument. For a tenant-specific dashboard, a small extractor can parse the tenant ID header once:

use ntex::http::Payload;
use ntex::web::{self, App, FromRequest, HttpRequest, InternalError};

struct TenantId(u32);

impl<St: web::State> FromRequest<St> for TenantId {
    type Error = InternalError<&'static str>;

    async fn from_request(
        _: &St,
        req: &HttpRequest,
        _: &mut Payload,
    ) -> Result<Self, Self::Error> {
        let value = req
            .headers()
            .get("x-tenant-id")
            .and_then(|value| value.to_str().ok())
            .ok_or_else(|| web::error::ErrorBadRequest("Missing tenant ID"))?;
        let id = value
            .parse::<u32>()
            .map_err(|_| web::error::ErrorBadRequest("Invalid tenant ID"))?;
        Ok(TenantId(id))
    }
}

async fn dashboard(tenant: TenantId) -> String {
    format!("Dashboard for tenant {}", tenant.0)
}

fn main() {
    let app = App::default().route("/dashboard", web::get().to(dashboard));
}

The extractor owns the parsed ID, so the handler does not borrow a header value from the request. Missing or nonnumeric headers produce 400, and the handler is never called. Because this extractor does not read the body, it can safely accompany Json<T> or another body extractor.

Parsing a tenant header is not authorization. Before using it to select data, check that the authenticated caller may access that tenant. The same pattern works for an API key: extract its header, then verify the credential against trusted application state. Keep secrets out of error messages and logs.

Handlers registered with Route::to_with_state() receive application state and request-local state before their extractor arguments. Extractors behave the same way as with Route::to(). They can use application state, but they do not receive the request-local state carried by WebRequest. See Web Application State for details.

Responders

Return a responder to let ntex build the HTTP response for you. Your handler can return any type that implements Responder.

Common responder types include:

ResponderResult
HttpResponse or HttpResponseBuilderThe response as configured
String, &String, or &'static str200 OK, text/plain; charset=utf-8
Bytes, BytesMut, or &'static [u8]200 OK, application/octet-stream
Json<T>200 OK, application/json
Form<T>200 OK, application/x-www-form-urlencoded
Option<T>The inner response, or 404 Not Found for None
Result<T, E>The inner response, or the error response produced by E
(T, StatusCode)The inner response with a different status code
Either<A, B>The response of whichever variant is returned
InternalError<T>The error response with its configured status
()200 OK with an empty body, for applications with () state

ntex converts the responder after the handler completes. The conversion receives both application state and the original request.

The error type in Result<T, E> must implement WebResponseError. See Web Application Errors for how errors become responses. Either is available as ntex::util::Either.

Use Responder::with_status() to change a responder’s status. To set a header, use Responder::with_header():

use ntex::http::StatusCode;
use ntex::web::{self, App, Responder};

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

async fn create_user() -> impl Responder {
    web::types::Json(User { id: 42 })
        .with_status(StatusCode::CREATED)
        .with_header("x-api-version", "1")
}

App::default().route(
    "/users",
    web::post().to(create_user),
);

These methods wrap the original responder, keeping its body and other headers. The wrapper then applies your status and headers. A configured header replaces values with the same name from the inner responder.

Calling with_header() again for the same name adds another value. Use CustomResponder::set_header() to replace the values set so far:

use ntex::web::Responder;

async fn negotiated() -> impl Responder {
    "hello"
        .with_header("vary", "accept")
        .with_header("vary", "accept-encoding") // `vary: accept` and `vary: accept-encoding`
        .set_header("vary", "*") // only `vary: *`
}

The status override applies to error responses too. On a Result, with_status() replaces the status regardless of which variant is returned. A (responder, StatusCode) tuple does the same.

For example, overriding the status with 201 Created sends a 400 Bad Request error as 201, keeping its error body. To set only the success status, customize the Ok value:

use ntex::http::StatusCode;
use ntex::web::{self, Responder, error::{ErrorBadRequest, InternalError}};

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

async fn create_user(
    name: web::types::Path<String>,
) -> Result<impl Responder, InternalError<&'static str>> {
    if name.is_empty() {
        return Err(ErrorBadRequest("name is required")); // stays 400
    }
    let user = User { name: name.into_inner() };
    Ok(web::types::Json(user).with_status(StatusCode::CREATED))
}

The same applies to with_header(): headers configured on a Result are added to error responses as well.

For simple handlers, a concrete responder such as Json<T> keeps the signature clear. Use impl Responder when the concrete wrapper type does not matter. Use Either<A, B> when branches produce different responder types.

Custom Responders

Implement Responder to return one of your own types directly from a handler. The asynchronous conversion can inspect application state or request metadata.

For example, several creation endpoints might share the convention that a new user response includes a JSON body and a Location header:

use ntex::web::{self, App, HttpRequest, HttpResponse, Responder};

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

impl<St: web::State> Responder<St> for CreatedUser {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> HttpResponse {
        HttpResponse::Created()
            .header("location", format!("/users/{}", self.id))
            .json(&self)
    }
}

async fn create_user() -> CreatedUser {
    CreatedUser {
        id: 42,
        name: "Ada".to_owned(),
    }
}

fn main() {
    let app = App::default().route("/users", web::post().to(create_user));
}

The handler returns a domain value; the responder keeps its HTTP convention in one place. For a one-off response, building HttpResponse directly is usually simpler. json(&self) serializes the value immediately, so the response does not borrow self after this method returns.

Streaming Responses

Return a streaming response when you can produce output a piece at a time. For example, a CSV export can send its header before all rows are available:

use std::io;

use futures::stream;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};

async fn export_users() -> HttpResponse {
    let chunks = stream::iter([
        Ok::<_, io::Error>(Bytes::from_static(b"id,name\n")),
        Ok(Bytes::from_static(b"42,Ada\n")),
        Ok(Bytes::from_static(b"43,Grace\n")),
    ]);
    HttpResponse::Ok()
        .content_type("text/csv; charset=utf-8")
        .streaming(chunks)
}

fn main() {
    let app = App::default().route("/users.csv", web::get().to(export_users));
}

This small example uses an in-memory stream so the mechanics are visible. For a large export, replace it with a producer that fetches or formats rows as needed, rather than first collecting every row in a Vec. The stream must be Unpin + 'static and yield Result<Bytes, E>, where E implements std::error::Error + 'static. It must own its data rather than borrow a handler-local variable.

Chunk boundaries are not application-message boundaries: an HTTP client may read two chunks together or split one across several reads. CSV uses line endings to delimit records. Other formats need their own framing.

Check permissions and other conditions that affect the HTTP status before returning the response. A stream error after headers have been sent cannot replace the status with a new error response. Test the final body as well as the headers; Testing covers response bodies and real-server tests for connection behavior.

Request and Response Streaming covers producer tasks, framing, known lengths, slow readers, compression, and Server-Sent Events.