0
0
Expressframework~30 mins

swagger-jsdoc setup in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Setup swagger-jsdoc in an Express App
📖 Scenario: You are building a simple Express server and want to add automatic API documentation using swagger-jsdoc.This helps developers understand your API endpoints easily.
🎯 Goal: Set up swagger-jsdoc in your Express app to generate API documentation from JSDoc comments.
📋 What You'll Learn
Create a basic Express app with a single route
Add swagger-jsdoc configuration with API info and path to API files
Generate swagger specification using swagger-jsdoc
Serve the swagger JSON at a route
💡 Why This Matters
🌍 Real World
APIs often need clear documentation so other developers can understand and use them easily. swagger-jsdoc helps generate this documentation automatically from code comments.
💼 Career
Knowing how to set up swagger-jsdoc is useful for backend developers working with Node.js and Express to create well-documented APIs.
Progress0 / 4 steps
1
Create a basic Express app with one route
Create an Express app by importing express, then create an app instance called app. Add a GET route at /hello that sends the text 'Hello World'.
Express
Need a hint?

Use require('express') to import Express and app.get to create a route.

2
Add swagger-jsdoc configuration object
Create a constant called swaggerOptions that is an object with a definition property. Inside definition, add openapi set to '3.0.0' and info with title as 'My API' and version as '1.0.0'. Also add apis as an array with the string './index.js'.
Express
Need a hint?

Define swaggerOptions with definition and apis keys as described.

3
Generate swagger specification using swagger-jsdoc
Import swaggerJSDoc from 'swagger-jsdoc'. Then create a constant called swaggerSpec by calling swaggerJSDoc(swaggerOptions).
Express
Need a hint?

Use require('swagger-jsdoc') to import and call it with swaggerOptions.

4
Serve the swagger JSON at a route
Add a GET route at /api-docs.json that sends the swaggerSpec JSON as the response. Then add app.listen(3000) to start the server on port 3000.
Express
Need a hint?

Use app.get to serve swaggerSpec as JSON and app.listen(3000) to start the server.