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 eg Postman, but I can't find any suitable methods in the SwaggerModule
, nor does the Swagger UI have any export button.
According to this github issue you can just stringify the created Swagger document
and eg 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);
如果您遵循https://docs.nestjs.com/recipes/swagger ,请尝试访问/api/json
而不是/api-json
。
As well as the solution shown to write to disk ( https://stackoverflow.com/a/51736406/5693245 ), you can still access on your own API endpoint.
As per docs , depending on whether you use swagger-ui-express
or fastify
to serve docs the location will be different
To generate and download a Swagger JSON file, navigate to http://localhost:3000/api-json (swagger-ui-express) or http://localhost:3000/api/json (fastify-swagger) in your browser (assuming that your Swagger documentation is available under http://localhost:3000/api).
It also depends on where you serve your API from, and assumes you use /api
. If this is not the case replace with your endpoint, or in case you are not using a base URL for swagger-ui-express
this would be http://localhost:3000/-json
Tested in Nestjs v9
Suppose the docs path is as follows
http://localhost:3000/docs
Get JSON
http://localhost:3000/docs-json
Get YAML
http://localhost:3000/docs-yaml
Tested in Nestjs v8
GET http://{host}:{port}/docs
Get JSON
GET http://{host}:{port}/docs/json
With the latest version (v8 as of writing) of NestJS, following the setup in the openapi documentation , you should be able to access the json document without any extra setup with
GET http://{host}:{port}/api-docs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.