Skip to content
NestRS

OpenAPI

Your REST API documents itself — an OpenAPI 3.1 spec and a bundled Swagger UI, composed from the route table and your types.

Import one module and your REST API documents itself. OpenApiModule serves an OpenAPI 3.1 document at GET /api-json and a bundled, offline Swagger UI at GET /api — composed from the route table and your Json<T> types. There is no spec to hand-write, and it cannot drift from the code: change a handler, the document changes with it.

nest-rs-openapi builds on schemars for the JSON Schema derivation and bundles Swagger UI as the offline browser asset — the framework wires both behind the route table so the spec composes itself.

Terminal window
cargo add nest-rs --features openapi

Add OpenApiModule to the app root, alongside the controllers it should document:

apps/api/src/module.rs (from the demo, abridged)
use nest_rs::core::{GlobalInterceptors, module};
// …
use nest_rs::openapi::OpenApiModule;
// …
#[module(
imports = [
// …
OpenApiModule,
// …
UsersHttpModule,
// … the rest of the HTTP modules
],
// …
)]
pub struct ApiModule;

That’s the whole opt-in. The module self-mounts both endpoints on the HttpTransport it imports — the one the app’s HTTP adapters serve on: same port, same CORS, no second server. The bare import reads <PREFIX>_OPENAPI__* from the .env cascade; pass an OpenApiConfig to OpenApiModule::for_root to pin it in code instead.

  • GET /api-json — the OpenAPI 3.1 document, composed from the route table your app serves. Every #[controller] your app mounts contributes its operations; nothing is listed by hand.
  • GET /api — a bundled Swagger UI. The assets ship inside the binary, so it works with no internet access and no CDN, and the page loads nothing from elsewhere: it carries its own Content-Security-Policy (scripts and requests from its own origin only, never framed), which a policy the deployment sets for every response does not replace, and Swagger UI’s online validator, which would send the document’s URL to swagger.io, is off.
  • GET /api-json/v{n} — one document per API version, and only under <PREFIX>_HTTP__VERSIONING=header or media_type. OpenAPI 3.1 keys operations by path, so two versions selected by a header cannot both be described at /posts. Under the default uri strategy the version is already in the path and /api-json describes every version at once. See Versioning.
  • Schemas for free. Request and response bodies are derived from your Json<T> payload types via schemars. An entity declared with #[expose] already produces its JSON Schema — the same type feeds the handler, the GraphQL schema, and this document, so the three stay in sync by construction. See Database.
Terminal window
$ curl -s http://localhost:3000/api-json | jq '.openapi, .info.title, (.paths | keys)'
"3.1.2"
"api"
[
"/users",
"/users/{id}"
]

Open http://localhost:3000/api for the interactive Swagger UI — try a request straight from the browser.

The document is complete without annotations. #[api(...)] adds what the signature cannot say — a summary, a description, the group it sits in:

crates/features/src/posts/http/controller.rs (from the demo)
#[post("/{id}/publish")]
#[authorize(Update, bind = PostsService)]
#[use_guards(PostAuthorGuard)]
#[api(
summary = "Publish a draft post",
description = "Transitions a draft to published and writes a publication audit row in the \
same transaction. The id loads the `Update`-authorized post through the \
service. Re-publishing an already published post returns RFC 9457 \
`application/problem+json` (409)."
)]
async fn publish(&self, post: Authorized<Update, PostEntity>) -> Result<Json<Post>, PostError> {
Ok(Json(self.svc.publish(post.into_inner()).await?))
}

An operation #[crud] generates takes its summary and description the same way, through api(create(…)) on the #[crud] line: users’ generated create is documented so.

#[api] takes eight keys — summary, description, tags(...), response = Type, multipart = Type, response_content_type = "type/subtype", error(status = Type) and deprecated = "YYYY-MM-DD" — and refuses any other at compile time. Path, method, parameters, request schema and success status come from the handler signature. OpenAPI operations covers each of them.

An entity decorated with #[expose] produces a wire DTO whose JsonSchema ends up in components.schemas the moment a handler returns Json<User>. The schema generator is shared across every route: payloads referenced from multiple handlers de-duplicate, and a User returned from GET /users/{id} is the same $ref as the one returned from the List endpoint.

The same type powers the GraphQL output type, the wire DTO the handler returns, and the JSON Schema in /api-json — change one column on the entity, all three move together. No hand-written schema, no annotation, nothing to drift.

The document composes from the route table, so everything in it is derived:

  • the whole info block and servers — the transport’s global_prefix, or / at the origin root;
  • every operation under paths, with its path, query and header parameters;
  • its request body, and the media type that body arrives as;
  • a shared components.schemas holding every type an operation reaches and nothing else, an id keeping format: uuid and a timestamp format: date-time;
  • a bearerAuth entry in components.securitySchemes, beside the scheme of any other a guard challenges with (a token endpoint’s basicAuth), per-operation security naming it on a route whose guards can answer 401, one requirement naming each scheme where a chain challenges two, since a chain runs every guard, and security: [] on a #[public] one no guard still challenges — a #[public] route whose handler reads as an Ambient<P> the principal a guard of its chain attaches, or whose later guard requires it, still challenges: its 401 answers a caller that guard did not identify;
  • the success status — a #[http_code]’s or a #[redirect]’s, or the one the return type states — or the 2XX range where only the handler knows it — and its body, by the schema the return type names or the media type it writes;
  • the error statuses an operation can actually produce, read off what it takes and the transport it runs on — 400 where a parameter or a body can be refused, or a header or media type strategy refuses a malformed version on every route once one is versioned, 404 where a path parameter or a version selects, 408 where a body can stall under the body-read deadline, 409 where a write can conflict, 413 everywhere, since the transport refuses a declared length past its cap before routing, and 415 where a body can be refused, 500 everywhere, 503 with its Retry-After under a request timeout, 403 where a posture’s ability can refuse the row or a CORS policy lists its origins — and every status the route’s guards declare, the app’s pool included: 401 with its WWW-Authenticate challenge, 429 and 503 with their Retry-After — as RFC 9457 ProblemDetails, or the body a guard or a request answers in its protocol’s own words, each beside the other where both can answer one status, and beside any body #[api(error(...))] declares;
  • the response headers the framework sends: the Location of a Created answer or a #[redirect], the Link of a Paginated answer’s next page, Deprecation on a deprecated route, and every #[response_header] with its value;
  • deprecated: true on a route #[api(deprecated = "…")] marks.

No operation lists what the connection answers before a request exists: a head the server cannot parse is answered 400, one past the 64 KiB read buffer 431, as is an HTTP/2 header list past 16 KiB, by the HTTP layer underneath, with no problem document, layer or correlation header. No route received it, and OpenAPI’s responses are an operation’s.

operationId is derived too, as <controller>_<handler>, mapped onto what an identifier can carry — PostsController::list publishes posts_list, and a raw handler r#type publishes …_r_type rather than an id with a # in it. Qualified by the controller because #[crud] names every resource’s handlers identically, and OpenAPI requires the id to be unique across the document: a generator meeting two lists either errors or renames one, so a method goes missing from the SDK. A versioned operation carries its version too (posts_list_v2).

What the composer does not derive, it leaves to you:

  • example / examples on inputs and responses. schemars derives the shape, and #[schemars(example = …)] on a field puts a sample in its schema; the document invents none.
  • A response header a handler sets itself on a Response it builds. The route table knows the ones the framework and #[response_header] send, not what a handler body writes.
  • A status a handler answers on its own outside 2XX. A (StatusCode, B) pair or a built Response answering a 404, or an Err of its own, is documented by #[api(error(404 = T))], as any body of your own is.
  • externalDocs, the document-level link to further reading.
  • OpenAPI 3.2. The document is 3.1.2, the 3.1 line’s current patch. A 3.2 document is valid with no other change, but the TypeScript client generators read it as 3.1 and silently drop what only 3.2 can say — a QUERY operation, a typed event stream — so the framework stays on the version every generator reads in full. An #[sse] route’s events are therefore typed string.
  • Which version /api-json describes, when the deployment names no default. It then aggregates every declared version and resolves a contested path to the highest one, naming the loser in a boot warn. Point a client at /api-json/v{n} when it needs one version’s shapes exactly.

Don’t hand-patch the document: it is composed at boot from the route table, so an out-of-band edit is lost the next time the app starts and breaks the no-drift invariant that makes the spec worth trusting. (Composed once, not per request — serving it is a string write.)

  • apps/api/ — mounts OpenApiModule next to REST + GraphQL.
  • crates/features/src/posts/http/controller.rs — real #[api(...)] usage; crates/features/src/users/http/controller.rs — api(get(…), create(…)) on a #[crud].
  • crates/nest-rs-openapi/ — OpenApiModule, OpenApiConfig, the document composer, the bundled Swagger UI.