Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swagger-ui-express Multiple Routes for Different API Documentation

I have 2 separate swagger API documentations which I want to run via swagger-ui-express NPM package, and my express server is starting fine on port 5000, but when I am trying to access any of the URL always getting the 404 error, Here is my app.js file and URL's for your reference:

Route 1: http://localhost:5000/edi Route 2: http://localhost:5000/ecom

const express    = require('express');
const router     = require('express').Router();
const swaggerUi  = require('swagger-ui-express');

const ediSwaggerDocument  = require('./edi-openapi.json');
const ecomSwaggerDocument = require('./ecom-openapi.json');

const SWAGGER_APP_PORT = process.env.SWAGGER_APP_PORT || 5000;

const app = express();

// Route Middleware to be called before serving Any Route
router.use('/', swaggerUi.serve); 

// Route - EDI RESTful API Documentaion 
router.get('/edi', swaggerUi.setup(ediSwaggerDocument)); 

// Route - eCommerce RESTful API Documentaion 
router.get('/ecom', swaggerUi.setup(ecomSwaggerDocument));

app.listen(SWAGGER_APP_PORT, () => console.log(`RESTful API Up and Running on Port ${SWAGGER_APP_PORT}`));
like image 870
luvcoding Avatar asked Oct 23 '25 17:10

luvcoding


2 Answers

Try the following configurations to hook swaggerUi with express-app


app.use("/edi", swaggerUi.serve, (...args) => swaggerUi.setup(ediSwaggerDocument)(...args));
app.use("/ecom", swaggerUi.serve, (...args) => swaggerUi.setup(ecomSwaggerDocument)(...args));


like image 103
Roy Lee Avatar answered Oct 26 '25 08:10

Roy Lee


I haven't dig enough into the swagger-ui-express but i think the problem comes from the function generateHTML (called in swaggerUi.setup). A global module variable (swaggerInit) is updated when called.

So the last call to generateHTML has side effects on every routes that use swaggerUi.setup middleware.

A quick fix is to generate HTML each time the route is called. According to the code snippet you provide, it should looks like :

 let swaggerDocEdi = require('./edi-openapi.json');
 let swaggerDocEcom= require('./ecom-openapi.json');
 let router = express.Router();

 router.use('/api/edi', swagger.serve, (req, res) => {
     let html = swagger.generateHTML(swaggerDocEdi);
     res.send(html);
 });

 router.use('/api/ecom', swagger.serve, (req, res) => {
     let html = swagger.generateHTML(swaggerDocEcom);
     res.send(html);
  });

Note that the global variable is still updated.

like image 41
Benoît Guérout Avatar answered Oct 26 '25 09:10

Benoît Guérout