Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Swagger documentation as JSON/YAML in NestJS

I've followed the instructions to create a Swagger documentation, and my documentation is now available using Swagger UI. I'd like to also generate the documentation as JSON or YAML so it's easy to import in e.g. Postman, but I can't find any suitable methods in the SwaggerModule, nor does the Swagger UI have any export button.

like image 472
Joakim Bugge Avatar asked Aug 07 '18 17:08

Joakim Bugge


2 Answers

According to this github issue you can just stringify the created Swagger document and e.g. write it to the file system like this:

const app = await NestFactory.create(ApplicationModule);
const options = new DocumentBuilder()
    .setTitle("Title")
    .setDescription("description")
    .setVersion("1.0")
    .build();
const document = SwaggerModule.createDocument(app, options);

fs.writeFileSync("./swagger-spec.json", JSON.stringify(document));
SwaggerModule.setup("/api", app, document);

await app.listen(80);
like image 52
Kim Kern Avatar answered Oct 13 '22 14:10

Kim Kern


Try visiting /api/json instead of /api-json if you followed https://docs.nestjs.com/recipes/swagger.

like image 22
JobaerAhamed Avatar answered Oct 13 '22 16:10

JobaerAhamed