# Nest and OpenAPI(Swagger): Integration for Development

* [Nest](https://docs.nestjs.com/openapi/introduction?utm_source=hashnode&utm_medium=hashnode%20rix&utm_campaign=rix_chatbot_answer), a Node.js framework, simplifies API development by providing a module that integrates with the [OpenAPI](https://notiz.dev/blog/openapi-in-nestjs/?utm_source=hashnode&utm_medium=hashnode%20rix&utm_campaign=rix_chatbot_answer) 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](https://stackoverflow.com/questions/64927411/how-to-generate-openapi-specification-with-nestjs-without-running-the-applicatio?utm_source=hashnode&utm_medium=hashnode+rix&utm_campaign=rix_chatbot_answer) redefines how API documentation is built, ensuring robust, performant, and impeccably documented APIs within a single workflow.
    

[Step-by-step instructions](https://ballardchalmers.com/resources/creating-a-rest-api-in-nestjs/?utm_source=hashnode&utm_medium=hashnode+rix&utm_campaign=rix_chatbot_answer) with thorough explanations for adding the required files and configurations to produce and set up [Swagger](https://codeburst.io/integrating-swagger-with-nestjs-9650594ab728) documentation for your [NestJS API](https://medium.com/swlh/create-an-api-rest-with-nestjs-1954723e8234):

### Step 1: Create a new NestJS project using the CLI:

```bash
nest new demo-api
cd demo-api
```

### Generate a REST API with CRUD endpoints

```bash
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](https://swagger.io/tools/swagger-editor/) and its Express UI library

```bash
npm install --save @nestjs/swagger swagger-ui-express
```

### Step 3: [Swagger](https://idratherbewriting.com/learnapidoc/pubapis_openapi_step2_info_object.html) configuration

* Open the main.ts file in the NestJS project's root directory.
    
* Import the following modules at the start of the file:
    

```typescript
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**

```typescript
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**](https://docs.nestjs.com/) **with the following configuration**

```typescript
  const document = SwaggerModule.createDocument(app, config);
```

**Set up the** [**Swagger UI**](https://swagger.io/docs/) **interface using the generated document:**

```typescript
  SwaggerModule.setup('api', app, document);
```

**Start your Nest application:**

```typescript
  await app.listen(3000);
}
bootstrap();
```

### Step 4: Examine the [Swagger UI](https://www.javatpoint.com/swagger)

```bash
npm run start
```

Navigate to [http://localhost:3000/api](http://localhost:3000/api) in your web browser. The [Swagger UI](https://swagger.io/tools/swagger-ui/download/) 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 <mark>src/demo folder</mark>).
    
* At the start of the file, add the following imports:
    

```typescript
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
```

* Add the [@ApiProperty](https://www.makeuseof.com/nestjs-apis-swagger-documentation/?utm_source=hashnode&utm_medium=hashnode+rix&utm_campaign=rix_chatbot_answer) and @[ApiPropertyOptional decorators](https://progressivecoder.com/a-quick-guide-to-nestjs-swagger-apiproperty/) to the CreateDemoDto class to alter the properties in the [Swagger](https://editor.swagger.io/) documentation:
    

```typescript
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 <mark>src/demo</mark> folder.
    
* At the start of the file, add the following imports:
    

```typescript
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:**

```typescript
@Post()
@ApiCreatedResponse({ description: 'Created Successfully' })
@ApiUnprocessableEntityResponse({ description: 'Bad Request' })
@ApiForbiddenResponse({ description: 'Unauthorized Request' })
create(@Body() createDemoDto: CreateDemoDto) {
  return this.demoService.create(createDemoDto);
}
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1692016671137/e591903f-c635-4473-b1bd-85c6002801f7.png align="center")

### **GET Methods:**

```typescript
@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:**

```typescript
@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:**

```typescript
@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](https://swagger.io/tools/swagger-ui/)

Start your Nest application

```bash
npm run start
```

* Navigate to [<mark>http://localhost:PORT&gt;/api</mark>](http://localhost:PORT%3E/api) in your web browser. Replace PORT&gt; 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](https://swagger.io/) documentation.
    

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You may produce and customize<a target="_blank" rel="noopener noreferrer nofollow" href="https://docs.nestjs.com/openapi/types-and-parameters" style="pointer-events: none"> Swagger documentation</a> for your NestJS API by following these instructions. The <a target="_blank" rel="noopener noreferrer nofollow" href="https://swagger.io/docs/specification/2-0/what-is-swagger/" style="pointer-events: none">Swagger </a>UI interface allows you to explore and understand your API's endpoints and features in an interactive and user-friendly manner.</div>
</div>

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,

[**ByteScrum Technologies Private Limited!**](https://www.bytescrum.com/) 🙏
