Nest and OpenAPI(Swagger): Integration for Development
Elevate API Development: Nest and OpenAPI - Where Code and Documentation Converge!
Table of contents
- Step 1: Create a new NestJS project using the CLI:
- Generate a REST API with CRUD endpoints
- Step 2: Install Swagger and its Express UI library
- Step 3: Swagger configuration
- Step 4: Examine the Swagger UI
- Step 5: Customize API Properties
- Step 6: Set API Responses
- POST Method:
- GET Methods:
- PATCH/UPDATE Method:
- DELETE Method:
- Step 7: Examine the Swagger UI
Nest, a Node.js framework, simplifies API development by providing a module that integrates with the OpenAPI specification.
By leveraging decorators, Nest allows developers to generate comprehensive API documentation without the need for separate tools or manual intervention.
This intuitive and automated process saves time, reduces human error, and enhances collaboration between development teams and API consumers.
Nest's integration with the OpenAPI specification redefines how API documentation is built, ensuring robust, performant, and impeccably documented APIs within a single workflow.
Step-by-step instructions with thorough explanations for adding the required files and configurations to produce and set up Swagger documentation for your NestJS API:
Step 1: Create a new NestJS project using the CLI:
nest new demo-api
cd demo-api
Generate a REST API with CRUD endpoints
nest generate resource demo --no-spec
Choose REST API as the transport layer and confirm producing CRUD entry points throughout the creation process.
Step 2: Install Swagger and its Express UI library
npm install --save @nestjs/swagger swagger-ui-express
Step 3: Swagger configuration
Open the main.ts file in the NestJS project's root directory.
Import the following modules at the start of the file:
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
Create a DocumentBuilder setting for your API documentation within the bootstrap function
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Demo API')
.setDescription('A Demo API with CRUD functionality')
.setVersion('1.0')
.build();
Generate the Swagger document with the following configuration
const document = SwaggerModule.createDocument(app, config);
Set up the Swagger UI interface using the generated document:
SwaggerModule.setup('api', app, document);
Start your Nest application:
await app.listen(3000);
}
bootstrap();
Step 4: Examine the Swagger UI
npm run start
Navigate to http://localhost:3000/api in your web browser. The Swagger UI interface should display your API documentation. It displays a list of all the endpoints you created in Step 1.
Step 5: Customize API Properties
Open the create-demo.dto.ts file, which should be in the same directory as your controller (most likely the src/demo folder).
At the start of the file, add the following imports:
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
- Add the @ApiProperty and @ApiPropertyOptional decorators to the CreateDemoDto class to alter the properties in the Swagger documentation:
export class CreateDemoDto {
@ApiProperty({
type: String,
description: 'This is a required property',
})
property: string;
@ApiPropertyOptional({
type: String,
description: 'This is an optional property',
})
optionalProperty?: string;
}
Step 6: Set API Responses
Open the demo.controller.ts file from the src/demo folder.
At the start of the file, add the following imports:
import { ApiTags, ApiCreatedResponse, ApiUnprocessableEntityResponse, ApiForbiddenResponse, ApiOkResponse, ApiNotFoundResponse, ApiUnprocessableEntityResponse } from '@nestjs/swagger';
- To set API replies for your controller methods, use the necessary decorators. Here are some examples of several methods:
POST Method:
@Post()
@ApiCreatedResponse({ description: 'Created Successfully' })
@ApiUnprocessableEntityResponse({ description: 'Bad Request' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
create(@Body() createDemoDto: CreateDemoDto) {
return this.demoService.create(createDemoDto);
}
GET Methods:
@Get()
@ApiOkResponse({ description: 'The resources were returned successfully' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
findAll() {
return this.demoService.findAll();
}
@Get(':id')
@ApiOkResponse({ description: 'The resource was returned successfully' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
@ApiNotFoundResponse({ description: 'Resource not found' })
findOne(@Param('id') id: string) {
return this.demoService.findOne(+id);
}
PATCH/UPDATE Method:
@Patch(':id')
@ApiOkResponse({ description: 'The resource was updated successfully' })
@ApiNotFoundResponse({ description: 'Resource not found' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
@ApiUnprocessableEntityResponse({ description: 'Bad Request' })
update(@Param('id') id: string, @Body() updateDemoDto: UpdateDemoDto) {
return this.demoService.update(+id, updateDemoDto);
}
DELETE Method:
@Delete(':id')
@ApiOkResponse({ description: 'The resource was returned successfully' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
@ApiNotFoundResponse({ description: 'Resource not found' })
remove(@Param('id') id: string) {
return this.demoService.remove(+id);
}
Step 7: Examine the Swagger UI
Start your Nest application
npm run start
Navigate to localhost:PORT>/api in your web browser. Replace PORT> with the port number of your application (often 3000).
You may now add tags, descriptions, and examples to your controller methods and DTOs to personalize your Swagger documentation.
Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.
Warm regards,
ByteScrum Blog Team,