0
0
Expressframework~5 mins

Swagger UI integration in Express

Choose your learning style9 modes available
Introduction

Swagger UI helps you see and test your API in a simple web page. It makes understanding and using your API easier.

You want to show your API details to other developers clearly.
You want to test your API endpoints without writing extra code.
You want to keep your API documentation updated automatically.
You want a friendly interface to explore your API during development.
Syntax
Express
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger.json' assert { type: 'json' };

const app = express();

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Use swagger-ui-express package to serve Swagger UI in Express.

The Swagger document is usually a JSON file describing your API.

Examples
This example serves Swagger UI at the /docs URL path.
Express
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger.json' assert { type: 'json' };

app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Enables the explorer feature to allow searching and filtering in Swagger UI.
Express
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, { explorer: true }));
Sample Program

This Express app has a simple /hello endpoint and serves Swagger UI at /api-docs. The Swagger JSON file describes the API endpoints.

Express
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger.json' assert { type: 'json' };

const app = express();

app.get('/hello', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
  console.log('Swagger UI available at http://localhost:3000/api-docs');
});
OutputSuccess
Important Notes

Make sure your Swagger JSON file is valid and describes your API correctly.

You can customize Swagger UI appearance and behavior with options in swaggerUi.setup().

Use browser developer tools to inspect the Swagger UI page and debug if needed.

Summary

Swagger UI integration shows your API in a friendly web page.

Use swagger-ui-express middleware in Express to serve it.

Keep your Swagger JSON updated to reflect your API changes.