Skip to main content

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

  1. Enable Swagger/OpenAPI in your API using the framework’s built-in support.

  2. Ensure the spec is available as JSON at a URL. Common defaults:

    FrameworkTypical JSON endpoint
    NestJS/docs-json or /api-json
    FastAPI/openapi.json
    Spring Boot/v3/api-docs
  3. Configure the docs site so it can fetch that URL. In docusaurus.config.ts, set specPath to your API’s spec URL (with the correct host and port), for example:

    ts
    userManagement: {
    specPath: 'http://localhost:3000/docs-json', // Your API's OpenAPI JSON URL
    outputDir: 'docs/openapi/user-management',
    // ...
    }
  4. Generate the docs: with the API running and the spec URL reachable, run:

    bash
    pnpm gen-api-docs -p user-management

    Or run pnpm gen-api-docs to 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 specPath in 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:

text
const 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 ENDPOINT
app.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:

text
const 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);
});