Export Swagger JSON from API
Newer versions of Swagger
In newer APIs (e.g. user-management), the OpenAPI/Swagger spec is usually exposed automatically by the framework. You do not need to create a custom route that builds and returns the JSON.
Expose the OpenAPI spec
-
Enable Swagger/OpenAPI in your API using the framework’s built-in support.
-
Ensure the spec is available as JSON at a URL. Common defaults:
Framework Typical JSON endpoint NestJS /docs-jsonor/api-jsonFastAPI /openapi.jsonSpring Boot /v3/api-docs -
Configure the docs site so it can fetch that URL. In
docusaurus.config.ts, setspecPathto your API’s spec URL (with the correct host and port), for example:tsuserManagement: {specPath: 'http://localhost:3000/docs-json', // Your API's OpenAPI JSON URLoutputDir: 'docs/openapi/user-management',// ...} -
Generate the docs: with the API running and the spec URL reachable, run:
bashpnpm gen-api-docs -p user-managementOr run
pnpm gen-api-docsto regenerate all API docs (legacy and new).
Notes
- The API must be running when you run
gen-api-docs, so the plugin can fetch the spec from the URL. - If your API uses a different port or path, update
specPathin the plugin config accordingly.
Older versions of Swagger
Before importing all of the routes to Docusaurus, it is necessary to create a route to export the JSON in the API. The following step will show you how.
Steps:
Create a exporting route
In the API swagger config file, create a endpoint to export the swagger JSON. Example:
textconst swaggerOptions = {definition: {openapi: '3.0.0',info: {title: 'API Mobilemed',version: '1.0.0',description: 'Documentação da API Mobilemed',},},apis: ['./routes/*.js'],};const swaggerDocs = swaggerJsdoc(swaggerOptions);// 🔹 JSON ENDPOINTapp.get('/api-docs.json', (req, res) => {res.setHeader('Content-Type', 'application/json');res.send(swaggerDocs);});
You can export all the of the documentation at once or separate them:
textconst exameRoutesOptions = {...swaggerOptions,apis: ['./routes/exame.js'],};const authenticationRoutesOptions = {...swaggerOptions,apis: ['./routes/authentication.js'],};const logoutRoutesOptions = {...swaggerOptions,apis: ['./routes/logout.js'],};const exameRoutesDocs = swaggerJsdoc(exameRoutesOptions);const authenticationRoutesDocs = swaggerJsdoc(authenticationRoutesOptions);const logoutRoutesDocs = swaggerJsdoc(logoutRoutesOptions);app.get('/api-docs/exame.json', (req, res) => {res.setHeader('Content-Type', 'application/json');res.send(exameRoutesDocs);});app.get('/api-docs/authentication.json', (req, res) => {res.setHeader('Content-Type', 'application/json');res.send(authenticationRoutesDocs);});app.get('/api-docs/logout.json', (req, res) => {res.setHeader('Content-Type', 'application/json');res.send(logoutRoutesDocs);});