Responses
Json<T>, status + body tuples, and the three response-shaping attributes — #[http_code], #[response_header], #[redirect].
A handler picks a return type, and the framework turns it into the
response. String, &'static str, Json<T>, a (StatusCode, Body)
pair, a built Response — anything that implements nest_rs::http’s
IntoResponse is a valid return, and so is a Result of one. When the status, a header, or a
redirect is the only thing changing, three attribute macros sit beside
the verb attribute and shape the response without touching the handler
body.
Returning typed JSON
Section titled “Returning typed JSON”Json<T> is the everyday case — serializes T, sets
Content-Type: application/json; charset=utf-8, and feeds the OpenAPI document with
the same JSON schema:
use nest_rs::core::output;use nest_rs::http::Json;
#[output]struct GreetReply { greeting: String,}
#[get("/me")]async fn me(&self) -> Json<GreetReply> { Json(GreetReply { greeting: self.svc.greeting() })}Status + body pairs
Section titled “Status + body pairs”A (StatusCode, T) pair answers T under that status, which the handler
computes on each call — useful when one call returns 202 Accepted and another
stays on 200:
use nest_rs::http::StatusCode;
#[post("/queue")]async fn enqueue(&self) -> (StatusCode, &'static str) { (StatusCode::ACCEPTED, "queued")}The OpenAPI document cannot name a status the handler computes, so it lists
the 2XX range with T’s
schema when T is a Json<_>, the media type T writes
when it is text or bytes, here text/plain, and a bare StatusCode the range
alone. A status that never varies is a #[http_code(N)], which the
document names.
A create names what it created
Section titled “A create names what it created”A 201 names what it created (RFC 9110 §15.3.2), and Created<T> says both in
the return type:
use nest_rs::http::{Created, Json, Result};
#[post("/posts")]async fn create(&self, Json(input): Json<CreatePost>) -> Result<Created<Json<Post>>> { let post = self.svc.create(input).await?; Ok(Created::at(post.id, Json(post)))}Created::at(id, body) answers 201 with Location: <collection>/<id>, the
collection being the path the caller addressed — global prefix and version
included, the client-controlled Host never named — and the id one
percent-encoded path segment, whatever it holds. The header is written
whoever answers it — a route, a self-mount’s
entry, a route registered by hand — and the OpenAPI document reads
the status, the Location and the body off the return type, alias included:
no #[http_code(201)], no #[api(response = …)], no &Request taken for its
path. The
#[crud] create answers the same type. A list that pages
answers Paginated<T> alike, its Link to the next page
(Pagination).
Shape a response declaratively
Section titled “Shape a response declaratively”When the handler body would otherwise return Ok(value) and the only
thing changing is the status, a header, or a redirect, three attribute
macros sit beside the verb attribute:
use nest_rs::http::{Json, Result, http_code, redirect, response_header};
#[post("/posts/import")]#[http_code(202)]#[response_header("x-cache-status", "miss")]async fn import(&self, Json(input): Json<ImportPosts>) -> Result<Json<ImportTicket>> { Ok(Json(self.svc.import(input).await?))}
#[get("/old-path")]#[redirect("/new-path", 301)]async fn moved(&self) {}#[http_code(N)]
Section titled “#[http_code(N)]”Overrides the response status on the success path. N must be in
100..=999 and is validated at compile time. When the handler returns a
Result and yields Err, the shaper short-circuits: the status the error
answers stands and #[http_code] never touches it — so a
202 handler that errors still returns the error’s 4xx/5xx, not
202. A Result is known by its type, not its spelling: nest_rs::http::Result<T>
renamed on import, or a type Outcome<T> = Result<T, MyError>, short-circuits
the same way. Mutually exclusive with #[redirect] — the two macros cannot both
decorate the same handler.
#[response_header("name", "value")]
Section titled “#[response_header("name", "value")]”Sets a header on the response, over any value the handler set; set-cookie alone
is appended. Repeatable; stack as many as the route needs. Two checks run at compile time:
- the header name must be lowercase ASCII (the HTTP/2 / HTTP/3 grammar);
- the value must be printable ASCII (no CR, LF, or NUL).
A typo (Cache-Control instead of cache-control, a stray newline in
the value) is caught by cargo build, never at runtime.
A header the route sets wins over the transport’s default for it: a
security header or Server:
is written only on a response that sets none.
#[redirect("url"[, status])]
Section titled “#[redirect("url"[, status])]”Sends a Location: <url> response without calling the handler body.
Status defaults to 307 and must be in 300..=399. The method’s
extractors still resolve (they are part of the request pipeline), but the
body is never executed — so the handler must have an empty body
(async fn moved(&self) {}). A non-empty body is a compile error, because
any side-effect work there would silently vanish; move such work into a
service the user is redirected to.
How shapers compose
Section titled “How shapers compose”Multiple shapers stack on the same handler. They apply in the order they appear in the source, but each one targets a different facet of the response (status, headers, body), so the order rarely matters in practice:
#[post("/posts")]#[response_header("x-cache-status", "miss")]#[response_header("link", "</posts>; rel=collection")]async fn create(&self, Json(input): Json<CreatePost>) -> Result<Created<Json<Post>>> { let post = self.svc.create(input).await?; Ok(Created::at(post.id, Json(post)))}The handler answers 201 with the post and its Location; the two
#[response_header] attributes set their headers. #[redirect] cannot
stack with #[http_code] — they decide the same facet (the response status)
two different ways.
A handler that returns a Result keeps its error contract intact: on
Err, the shaper short-circuits before #[http_code] runs, so the
error’s status and body survive unchanged. #[http_code]
only ever rewrites the success status.
When not to reach for a shaper
Section titled “When not to reach for a shaper”The three macros are declarative shortcuts for the common cases. When the response wiring is genuinely conditional — the status depends on whether an entity already existed, the headers depend on the resolved user — go back to a plain tuple return and let the handler decide:
use nest_rs::http::{Created, IntoResponse, Json, Response, Result};
#[post("/posts")]async fn upsert(&self, Json(input): Json<CreatePost>) -> Result<Response> { let (post, created) = self.svc.upsert(input).await?; Ok(match created { true => Created::at(post.id, Json(post)).into_response(), false => Json(post).into_response(), })}A Created turned into a Response keeps its Location: the route still
writes it. What the document cannot read off a Response is the status, so
such a route documents
the 2XX range, and no
Location.
The shapers are best when the value is the same on every call — that’s why they live on the attribute line, not in the handler body.
Going further
Section titled “Going further”- Errors — when the handler returns
Err(...):ToProblem,ProblemDetails, RFC 9457. - Controllers & routes — back to the route table.
- OpenAPI —
Json<T>and the response shape feed the generated spec automatically.