Building an API documentation using Swagger (now known as OpenAPI) and Node.js can significantly improve the developer experience by providing an interactive and easy-to-understand documentation of your API. Here's a step-by-step guide on how to create API documentation using Swagger and Node.js:
- Set up a Node.js project:
Create a new directory for your project and navigate to it in the terminal. Next, initialize a new Node.js project by running:
npm init
Install the required dependencies:
npm install express --save
npm install swagger-ui-express --save
npm install yamljs --save
Create a new file app.js:
touch app.js
- Create a basic Express server:
Redacting the app.js, add the following code to initialize a basic Express server:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
- Add Swagger UI to your server:
In app.js, add the following code to import and configure Swagger UI:
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
This code imports the Swagger UI Express module, loads the swagger.yaml configuration file (which we will create in the next step), and sets up a new route /api-docs for the Swagger UI.
- Create API definition using OpenAPI in a
swagger.yaml file:
In the project folder, create a new file named swagger.yaml:
touch swagger.yaml
Open the swagger.yaml file and start defining your API, following the OpenAPI Specification. Here is a basic example:
openapi: "3.0.0"
info:
version: 1.0.0
title: Sample API
description: A sample API documentation using Swagger and Node.js
servers:
- url: http://localhost:3000
description: Local development server
paths:
/:
get:
summary: Get hello message
operationId: getHelloMessage
responses:
"200":
description: Success
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: Hello World!
- Test your API documentation:
Now that you have your API defined in the swagger.yaml file and your Express server is set up, you can start your server by running:
node app.js
Navigate to http://localhost:3000/api-docs in your web browser to view and test your interactive API documentation powered by Swagger UI.
Remember, you can always extend and update your swagger.yaml to include new endpoints, request and response types, and other API configurations.