W02 Learning Activity: Swagger Documentation
Overview
- Purpose: Learn about Swagger API documentation.
- Task: Read the following information and complete the activity instructions below.
In the previous Week 02 activities, you learned how write routes change MongoDB data and how documents can reference related documents. In this activity, you will add interactive Swagger documentation to your existing Books API project.
Swagger will become your main testing tool for Week 02. After this activity, your API should have an /api-docs route where you can read the documentation and send requests from the browser.
Complete these steps in the same Week 01 Books API project. The Swagger setup should be committed and deployed with the rest of your API code.
Preparation Material
What Swagger does
Swagger is a common way to document REST APIs. It describes the routes, methods, parameters, request bodies, response bodies, and status codes that an API supports.
Swagger UI turns that documentation into an interactive web page. Instead of only reading the API docs, you can click Try it out, enter request values, and send real requests to your API.
Documentation and testing
Good Swagger documentation is both a reference and a testing surface. If your Swagger docs are inaccurate, your tests may hide bugs or confuse API clients.
Two packages you will use
swagger-ui-expressserves the interactive Swagger UI from your Express app.swagger-jsdocreads OpenAPI comments from your route files and generates aswagger.jsonfile during development.
Why one package is a development dependency
swagger-jsdoc is only needed when you generate the documentation file. The deployed app will serve the generated swagger.json file with swagger-ui-express, so swagger-jsdoc should be installed as a development dependency.
Swagger and OpenAPI
The word Swagger is often used for the interactive documentation tools. The API description format is OpenAPI. In this course, generate OpenAPI 3 documentation so your examples match current API documentation patterns.
How the generation process works
In this activity, you will install Swagger packages, create a swagger.js generator file, add OpenAPI comments to your route file, and then run npm run swagger.
When you run that command, swagger-jsdoc looks through the files listed in swagger.js, finds comments marked with @openapi, and uses those comments to generate a swagger.json file. Then your Express app uses swagger-ui-express to display that generated documentation at /api-docs.
swagger-jsdoc also recognizes the older @swagger marker as an equivalent alternative to @openapi. This course uses @openapi consistently, so use that marker in your own comments.
What OpenAPI comments do
OpenAPI comments are special documentation blocks that swagger-jsdoc reads when it generates swagger.json. They do not change how your route works. Instead, they describe the route so Swagger UI can show the method, path, parameters, request body, possible responses, and status codes.
A good OpenAPI comment should include the route path, the HTTP method, a short summary, a tag for grouping related routes, any path parameters, any request body fields, and the expected success and error responses. The comments should match the real behavior of your controller. For example, if a product route returns 404 when a product is missing, the OpenAPI comment should document that 404 response.
OpenAPI comment syntax
Each OpenAPI comment starts with a normal JavaScript block comment and an @openapi marker. Inside the comment, the indentation matters because the content is written in YAML. The path comes first, then the HTTP method is nested under that path.
/**
* @openapi
* /products:
* get:
* summary: Get all products
* tags:
* - Products
*/
router.get('/products', getProductsHandler);
For route parameters, use braces in the OpenAPI path, such as /products/{id}, then describe the parameter in a parameters section. Response status codes are listed under responses.
/**
* @openapi
* /products/{id}:
* get:
* summary: Get one product by id
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Product returned successfully
* 404:
* description: Product not found
*/
router.get('/products/:id', getProductByIdHandler);
For routes that receive JSON, such as POST and PUT routes, document the incoming body with a requestBody section. This tells Swagger UI to show a JSON editor when you test the route.
/**
* @openapi
* /products:
* post:
* summary: Create a product
* tags:
* - Products
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - id
* - name
* - price
* properties:
* id:
* type: string
* name:
* type: string
* price:
* type: number
* example:
* id: p4
* name: Trail Backpack
* price: 79.99
* responses:
* 201:
* description: Product created successfully
* 400:
* description: Invalid product data
*/
router.post('/products', createProductHandler);
When testing this kind of route in Swagger UI, click Try it out. Swagger will show a Request body box with the example JSON. Edit the JSON as needed, then click Execute. The request body shown in Swagger should match what your controller expects in req.body.
Use AI to help write the OpenAPI comments
Writing OpenAPI comments is a task that AI can do very well. It is recommended to let AI draft these comments for your routes, then carefully review the result to make sure the paths, parameters, request bodies, status codes, and response descriptions match what your code actually does.
Activity Instructions
Install the Swagger packages
Open your Week 01 Books API project in VS Code. Then install the packages you will use for Swagger.
npm install swagger-ui-express
npm install --save-dev swagger-jsdoc
Create a Swagger generator file
Create a file named swagger.js in the root of your project. This file will define the OpenAPI settings, tell swagger-jsdoc where to find your route comments, and write the generated documentation to swagger.json.
import { writeFileSync } from 'node:fs';
import swaggerJsdoc from 'swagger-jsdoc';
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Books API',
version: '1.0.0',
description: 'A simple API for working with books'
},
servers: [
{
url: '/',
description: 'Current server'
}
]
},
apis: ['./src/router.js', './app.js']
};
const swaggerSpec = swaggerJsdoc(options);
writeFileSync('./swagger.json', JSON.stringify(swaggerSpec, null, 2));
console.log('Swagger documentation generated.');
Use the Week 01 Project
Your project should follow the route structure from the Week 01 instructions. If your route files or route connections are different from the course instructions, fix your project structure before continuing instead of changing the Swagger setup to match a different organization.
Add OpenAPI comments to your routes
Open src/router.js. Ask AI to generate OpenAPI documentation comments for the Week 01 book routes in that file. Make sure the generated comments are placed directly above the matching route definitions.
You can use a prompt like this:
Generate swagger-jsdoc OpenAPI comments for the routes in this file. Use OpenAPI 3 syntax. Document
GET /booksandGET /books/:id, including tags, path parameters, and success and error responses. Do not change the route code.
After AI generates the comments, review them carefully. Make sure /books/:id is documented as /books/{id}, the response status codes match your controller behavior, and the comments are attached to the correct route definitions.
Example OpenAPI Comments (click to expand)
/**
* @openapi
* /books:
* get:
* summary: Get all books
* tags:
* - Books
* responses:
* 200:
* description: Books returned successfully
* 500:
* description: Unable to retrieve books
*/
router.get('/books', getBooksHandler);
/**
* @openapi
* /books/{id}:
* get:
* summary: Get one book by id
* tags:
* - Books
* parameters:
* - in: path
* name: id
* required: true
* description: The custom book id, such as b1
* schema:
* type: string
* responses:
* 200:
* description: Book returned successfully
* 404:
* description: Book not found
* 500:
* description: Unable to retrieve book
*/
router.get('/books/:id', getBookByIdHandler);
Add a script to generate Swagger docs
Open package.json and add a script named swagger.
"scripts": {
"start": "node --env-file=.env server.js",
"dev": "nodemon --env-file=.env server.js",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"swagger": "node swagger.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Then generate the documentation file:
npm run swagger
After the command finishes, confirm that swagger.json exists in your project. Regenerate swagger.json whenever you change routes or OpenAPI comments. Commit the generated file so Render can serve the docs without needing swagger-jsdoc in production.
Serve Swagger UI from Express
In app.js, import the Swagger UI package and the generated Swagger document. Then connect the /api-docs route.
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger.json' with { type: 'json' };
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Place the app.use('/api-docs', ...) line after the Express app is created.
After generating swagger.json, review the documented paths, request bodies, responses, and status codes carefully. The docs should describe the real API contract.
Verify your routes in Swagger
- Start your app with
npm run dev. - Open http://127.0.0.1:3000/api-docs.
- Confirm that your Week 01 routes appear, including
GET /booksandGET /books/{id}. - Use Try it out and Execute to test both book routes.
- If a route is missing or unclear, update the OpenAPI comments near the route, run
npm run swaggeragain, then restart your app.
Commit and deploy the Swagger setup
When Swagger works locally, commit the changes and deploy them. Since this setup is part of a learning activity and is not connected to a GitHub issue for your assignment, it is okay to push this directly to main instead of creating a pull request if you would like.
After deployment, open your Render URL with /api-docs at the end and confirm that Swagger loads from the deployed app.
- Run
npm run swagger. - Commit the Swagger setup file, route comments, package changes, and generated
swagger.json. - Push the commit to
main, or use a pull request if you prefer to practice that workflow. - Wait for Render to deploy the latest commit. If the deploy does not run, click Manual Deploy and choose From last commit.
- If the deploy fails, review the Render logs, fix the issue, and deploy again.
- Open your deployed
/api-docsroute and test the routes from Swagger UI.
Troubleshoot common Swagger problems
- If
/api-docsdoes not load, confirm thatswagger-ui-expressis installed and imported correctly. - If
swagger-jsdocwill not install, update Node.js to the current LTS version and try the install command again. - If Render cannot find
swagger.json, confirm the file was generated and committed. - If a route is missing, confirm the route file is included in the
apislist inswagger.js. - If Swagger shows a YAML error, check the spacing in your OpenAPI comments. YAML indentation must be consistent.
- If Swagger accepts fields your API does not use, update either the docs or the code so they match.
Next Step
You have now completed all of the learning activities for this week. Return to Canvas to take the W02 Learning Activities quiz.
Other Links:
- Return to: Week Overview | Course Home