Careeroza
Swagger Setup
Install and Mount
OpenAPI is a standard JSON/YAML description of a REST API. Swagger UI turns it into an interactive page where frontend developers and testers can try every endpoint.
Example
npm i @nestjs/swaggerExample output
added 3 packages in 3s
src/main.ts
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('ShopEase API')
.setDescription('Products, cart, orders and payments for the ShopEase storefront')
.setVersion('1.0')
.addBearerAuth()
.addServer('http://localhost:3000', 'Local')
.addServer('https://api.shopease.in', 'Production')
.build();
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, documentFactory, {
jsonDocumentUrl: 'docs/json',
swaggerOptions: { persistAuthorization: true },
});
await app.listen(3000);
}
bootstrap();Example
Open http://localhost:3000/docs in a browser, or fetch the raw spec:
curl -s http://localhost:3000/docs/json | head -c 300Example output
{"openapi":"3.0.0","paths":{"/products":{"get":{"operationId":"ProductsController_findAll","parameters":[{"name":"category","required":false,"in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array",...The CLI Plugin
Without help, Swagger cannot see TypeScript types at runtime. The Nest CLI plugin reads your DTOs at compile time and adds @ApiProperty() for you (including optional fields and class-validator rules).
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": [
{ "name": "@nestjs/swagger", "options": { "classValidatorShim": true, "introspectComments": true } }
]
}
}Note: The plugin only processes files named *.dto.ts and *.entity.ts by default.