Document routes and HTTP errors
12.6.0
An OpenAPI document describes how to call an API. Document status codes and payload shapes that clients can depend on.
On this page
Expose the OpenAPI document
Install @nestjs/swagger and build an OpenAPI configuration during bootstrap. SwaggerModule can generate the document and serve Swagger UI. Describe request and response DTO fields with decorators or the CLI plugin where appropriate.
// At the top of main.ts
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
// Inside bootstrap, after NestFactory.create(...)
const config = new DocumentBuilder()
.setTitle("Catalog API")
.setVersion("1.0")
.build();
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup("docs", app, documentFactory);
Return a status that matches the failure
BadRequestException suits invalid input. NotFoundException suits a missing resource. Add an exception filter when you need a defined error shape. Test the status and body of both successful responses and known errors.
import { BadRequestException, NotFoundException } from "@nestjs/common";
function findProduct(id: number, products: Map<number, string>) {
if (!Number.isInteger(id) || id < 1) {
throw new BadRequestException("Use a positive integer product ID.");
}
const name = products.get(id);
if (name === undefined) {
throw new NotFoundException("Product not found.");
}
return { id, name };
}