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.
Install
Section titled “Install”cargo add nest-rs --features openapiWire it in
Section titled “Wire it in”Add OpenApiModule to the app root, alongside the controllers it
should document:
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.
What you get
Section titled “What you get”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 ownContent-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=headerormedia_type. OpenAPI 3.1 keys operations by path, so two versions selected by a header cannot both be described at/posts. Under the defaulturistrategy the version is already in the path and/api-jsondescribes every version at once. See Versioning.- Schemas for free. Request and response bodies are derived from your
Json<T>payload types viaschemars. 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.
Run it
Section titled “Run it”$ 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.
Describe an operation
Section titled “Describe an operation”The document is complete without annotations. #[api(...)] adds what the
signature cannot say — a summary, a description, the group it sits in:
#[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.
Schemas from #[expose]
Section titled “Schemas from #[expose]”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.
Limits
Section titled “Limits”The document composes from the route table, so everything in it is derived:
- the whole
infoblock andservers— the transport’sglobal_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.schemasholding every type an operation reaches and nothing else, an id keepingformat: uuidand a timestampformat: date-time; - a
bearerAuthentry incomponents.securitySchemes, beside the scheme of any other a guard challenges with (a token endpoint’sbasicAuth), per-operationsecuritynaming it on a route whose guards can answer401, one requirement naming each scheme where a chain challenges two, since a chain runs every guard, andsecurity: []on a#[public]one no guard still challenges — a#[public]route whose handler reads as anAmbient<P>the principal a guard of its chain attaches, or whose later guard requires it, still challenges: its401answers 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 the2XXrange 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 —
400where 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,404where a path parameter or a version selects,408where a body can stall under the body-read deadline,409where a write can conflict,413everywhere, since the transport refuses a declared length past its cap before routing, and415where a body can be refused,500everywhere,503with itsRetry-Afterunder a request timeout,403where 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:401with itsWWW-Authenticatechallenge,429and503with theirRetry-After— as RFC 9457ProblemDetails, 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
Locationof aCreatedanswer or a#[redirect], theLinkof aPaginatedanswer’s next page,Deprecationon a deprecated route, and every#[response_header]with its value; deprecated: trueon 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/exampleson 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
Responseit 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 builtResponseanswering a404, or anErrof 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
QUERYoperation, a typed event stream — so the framework stays on the version every generator reads in full. An#[sse]route’s events are therefore typedstring. - Which version
/api-jsondescribes, 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 bootwarn. 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.)
Reference
Section titled “Reference”apps/api/— mountsOpenApiModulenext 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.
Going further
Section titled “Going further”- OpenAPI operations — bodies, headers, error responses, tags and deprecation, as a handler declares them.
- OpenAPI configuration — the
infoblock, the switch, the committed document. - Typed TypeScript clients — generate the frontend’s client and query hooks from this document.
- Security — the guards that decide which operations carry
security.