# NestJSでOpenAPIツール「swagger」を生成する

1 min read
Table of Contents

依存関係をインストールする

npm install --save @nestjs/swagger

main.tsを編集する

async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Swaggerの記述
const config = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();

後は上の記述を編集し、http://localhost:3000/api/を開けば作成されている。

非常に楽なので活用していきたい。

APIをグルーピングする

これだとcatsというタグができるがその中は空になり、すべてがdefaultにグルーピングされる。

任意のグルーピングを作りたい時は、hoge.controller.tsを下記のように変更する。

import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@Controller('hoge')
@ApiTags('hoge')
export class HogeController {
constructor(private readonly sService: HogeService) {}

これで意図した形になる。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments