Extractors
The full HTTP extractor surface — JSON, headers, raw body, client IP, request-scoped providers, guard-attached context.
An extractor pulls a typed value out of the request before the handler
runs. Path<T>, Query<T>, Json<T> and Form<T> cover the request line,
query string, JSON body and form body; beside them sit the framework-specific
extractors:
the typed header reader Header<T>, the
raw-body reader RawBody, the spoofable but observation-grade
ClientIp, the request-scoped DI resolver Scoped<T> and the
guard-attached context reader Ambient<T>. A handler that needs
the request itself — its URI, a header no DTO names — takes req: &Request.
This page is the reference: one extractor, one example, one rule. The
Guards for Ambient<T> and
Provider scopes for Scoped<T> — tell the story.
Json<T> — typed JSON in and out
Section titled “Json<T> — typed JSON in and out”Parses the request body into T; rejects a body that does not decode with
400, naming where — JSON body at `title`: missing — and never the value.
Works as a return type too — serializes T, sets
Content-Type: application/json; charset=utf-8, and feeds the OpenAPI document with
the same schema:
use nest_rs::core::{input, output};use nest_rs::http::{Json, Path, Result};use uuid::Uuid;
#[input]struct RenamePost { title: String }
#[output]struct Post { id: Uuid, title: String }
#[put("/posts/{id}/title")]async fn rename(&self, id: Path<Uuid>, Json(body): Json<RenamePost>) -> Result<Json<Post>> { Ok(Json(self.svc.rename(*id, body.title).await?))}Validation — the rules a type declares
Section titled “Validation — the rules a type declares”Every extractor’s value is held to the validator
rules its type declares, after the guards and before the handler, with nothing
to wrap. Json<T> is the usual carrier, and Query<T>, Form<T>, Path<T>
and Header<T> answer the same way:
use nest_rs::http::{Created, Json, Result};use nest_rs::core::input;
#[input]struct CreateUser { #[validate(length(min = 1))] name: String, #[validate(email)] email: String,}#[input] carries Serialize, Deserialize, Validate and JsonSchema,
so a DTO behind it needs no second derive — not for validation, not for the
OpenAPI document, and not to come back out as Json<T>. A DTO derived by hand
carries all four itself; adding one of them next to #[input] is a
conflicting impl (E0119). A reply the route only sends takes #[output],
Serialize and JsonSchema alone.
#[post("/users")]async fn create(&self, Json(body): Json<CreateUser>) -> Result<Created<Json<User>>> { let user = self.svc.create(body).await?; Ok(Created::at(user.id, Json(User::from(&user))))}A validation failure returns 400 with a structured field-level error
list — no manual checks in the handler. The rest is a create’s own answer, a
201 naming what it made, which Responses covers.
Piped<P, E> — transform at the edge
Section titled “Piped<P, E> — transform at the edge”Piped<P, E> applies any transport-agnostic pipe to
the value extractor E produced, once that value passed its rules, and binds
the pipe’s output:
use nest_rs::http::Path;use nest_rs::pipes::{ParseUuid, Piped};use nest_rs::http::Json;
#[get("/posts/{id}")]async fn show(&self, Piped(id): Piped<ParseUuid, Path<String>>) -> Json<Post> { Json(self.svc.find(id))}Piped is no extractor of its own: #[routes] reads it where the signature
spells it out, so a type alias of it is a compile error naming FromRequest
rather than a parameter that skips its source’s rules.
Header<T> — typed request headers
Section titled “Header<T> — typed request headers”The header-map twin of Query<T>: one struct field per header,
#[serde(rename = "…")] spelling the wire name, and an Option<_>
field marking the header optional. Lookup is case-insensitive, as HTTP
header names are, and values are parsed into the field’s type — a
u32 field is an integer, not a string you parse in the handler.
use nest_rs::http::{Header, SseStream};use serde::Deserialize;use schemars::JsonSchema;
#[derive(Deserialize, JsonSchema)]struct StreamResume { #[serde(rename = "Last-Event-ID")] last_event_id: Option<u32>,}
#[sse("/events")]async fn events(&self, resume: Header<StreamResume>) -> SseStream { self.svc.stream_from(resume.into_inner().last_event_id)}A missing required header, or a value that does not parse, is rejected
with the same RFC 9457 application/problem+json 400 a validation
failure carries. The rejection names the header and never quotes its
value — a header is where credentials travel, and a 400 body is
logged, cached and proxied.
Each property becomes an in: header parameter in the
OpenAPI document, required following the schema. It
composes like every other extractor: the rules its DTO declares hold,
and Piped<P, Header<T>> pipes it.
RawBody — exact bytes, with a size cap
Section titled “RawBody — exact bytes, with a size cap”Some handlers need the exact byte string before any parsing — a proxied
protobuf body, a document stored as it was sent. RawBody reads the whole body
into Bytes, capped at the transport’s
max_body_bytes (RawBody::DEFAULT_LIMIT, 2 MiB, by default). Past the cap the
request is answered 413 Content Too Large — never silently truncated, never
buffered unbounded. Like every extractor it reads after the guards, so a
refused request never had its body read.
use nest_rs::http::{Path, RawBody, Result};use uuid::Uuid;
#[put("/{id}/source")]async fn replace_source(&self, id: Path<Uuid>, body: RawBody) -> Result<()> { self.svc.replace_source(*id, body.into_inner()).await}A webhook’s signature is a credential, so it is verified in a guard that reads the same bytes and hands them on, never in the handler — see Read the body in a guard.
For a tighter cap on a specific route, take the body and read it under your own:
use nest_rs::http::{Body, Path, Result};use uuid::Uuid;
#[put("/{id}/summary")]async fn replace_summary(&self, id: Path<Uuid>, body: Body) -> Result<()> { let summary = body.into_bytes_limit(16 * 1024).await?; self.svc.replace_summary(*id, summary).await}Anything that can deserialize through Json<T> should use that instead —
RawBody is for handlers that genuinely care about the bytes.
ClientIp — best-effort, observation-grade
Section titled “ClientIp — best-effort, observation-grade”ClientIp is the transport peer, or the client a proxy you listed in
<PREFIX>_HTTP__TRUSTED_PROXIES names — the rightmost hop, never a header a
caller set. Client IP is how it resolves, and what to list
behind each proxy.
Scoped<T> — resolve a request-scoped provider
Section titled “Scoped<T> — resolve a request-scoped provider”A #[injectable(scope = request)] provider is built once per request —
useful for anything that should not outlive the response (a SQL
transaction handle, a per-request audit batch, a user-specific cache).
Scoped<T> is how a handler reads it back:
use nest_rs::core::injectable;use nest_rs::core::Scoped;use nest_rs::http::Json;
#[injectable(scope = request)]pub struct PerRequestAudit { /* ... */ }
#[get("/posts")]async fn list(&self, audit: Scoped<PerRequestAudit>) -> Json<Vec<Post>> { audit.note("list_posts"); Json(self.svc.list())}Two contracts hold:
Scoped<T>falls back to a singleton if no scoped factory exists forT— convenient, but a singleton should still be reached via plain#[inject]on the controller. ReserveScoped<T>for genuinely request-scoped state.- The framework installs the request scope as the outermost HTTP wrap
(before guards and interceptors). A provider the request still cannot
reach — the scope not installed, or
Toffered by no module — answers an opaque500, and the type goes to anerrorline onnest_rs::http, never to the client.
See Provider scopes for the scope rules — a request-scoped provider may inject singletons and other request-scoped providers, one instance each per request; a singleton injects neither.
Ambient<T> — read context a guard attached
Section titled “Ambient<T> — read context a guard attached”A guard runs before the handler, can short-circuit with a response, and
can attach a typed value for the rest of the request. Ambient<T> is how the
handler reads that value back:
#[get("/mine")]async fn mine(&self, caller: Ambient<Claims>) -> Result<Json<Vec<Post>>, PostError> { Ok(Json(self.svc.written_by(&caller.sub).await?))}caller is the principal the controller’s AuthnGuard attached.
Ambient<T> rejects with 500 if T is absent — a missing context means
the guard that should have set it never ran on this route (a wiring bug,
not a client error). T implements AmbientValue and Clone; the value is
cloned out of the ambient context, so a large one goes in a newtype holding an
Arc (struct Catalog(Arc<Entries>)), which implements AmbientValue itself.
Ambient<T> is core’s, nest_rs::core::Ambient, and the same parameter on every
edge: a GraphQL operation, a WebSocket message and an MCP tool read what their
guards attached the same way, and none of them lists it among the arguments
its protocol describes. A route reads the parameter by its type, so a type
alias of it (type Me = Ambient<Claims>;) reads as the name does; the other
three find it by its name, before any type is known, so there an alias of
Ambient<T> — or of Scoped<T> — is a compile error saying to write it out.
The canonical use is the authenticated principal: AuthnGuard runs the
strategy, then attaches a Claims (or whatever the resource server’s
principal is). Every authenticated handler reads it as auth: Ambient<Claims>.
On a #[public] route, a handler reading Ambient<Claims>, under that name or an
alias, needs the caller the guard identifies: one it did not is refused at the guard stage, before any other
argument is read, with the 401 a rejected credential earned
(Bearer error="invalid_token") or, for a caller that sent none, the plain
challenge, and the route’s document lists that 401. A handler that serves a
visitor too reads the principal with nest_rs::core::ambient::<Claims>(), an
Option.
See Guards for how to attach a value, and for the design rule (guards gate and attach; handlers read).
#[meta(EXPR)] and #[public] — what a guard reads
Section titled “#[meta(EXPR)] and #[public] — what a guard reads”Neither is an extractor. #[meta(EXPR)] declares a typed value on a route or its
controller — a rate-limit quota, the roles a route needs — and #[public] its
posture; a guard reads both through cx.reflector() at decision time, and the
handler never does: route metadata and the
posture.
Going further
Section titled “Going further”- Guards — write a guard that attaches
Ambient<T>. - Provider scopes — request-scoped providers and
the rules
Scoped<T>reads. - Pipes — write a pipe and apply it through
Piped<P, E>. - Responses — turn the value back into a response.