How to add Swagger UI to an existing Node.js and Express.js project
How to add Swagger UI to an existing Node.js and Express.js project
In this tutorial, we’ll be learning how to add swagger to an existing Node and Express.js. As we already learned in Part 1 — How to create a REST API with Express.js and Node.js (source code Part 1), and now we will add swagger in this project.
Before we start please find below the important definitions:
- Swagger — Swagger is an open-source software framework backed by a large ecosystem of tools that help developers design, build, document, and consume RESTful web services
- Swagger provides a set of great tools for designing APIs and improving the work with web services
a) Swagger Editor — Swagger Editor is an open-source editor to design, define and document RESTful APIs in the Swagger specification.
b) Swagger Codegen — Swagger Codegen is an open-source project which allows the generation of API client libraries (SDK generation), server stubs, and documentation automatically from an OpenAPI Specification.
c) Swagger UI — Swagger UI allows the development team to visualize and interact with the API resources without having any of the implementation logic in place. UI presentation of the APIs is user friendly and easy to understand, with all logic complexity kept behind the screen.
d) Swagger Inspector — A tool for testing and auto-generating OpenAPI documentation for any API. Swagger Inspector allows you to easily validate and test APIs with no limits on what you test. Tests are automatically saved in the cloud with simple access.
3. The OpenAPI Specification, originally known as the Swagger Specification, is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services.
In this project, as we already have an existing RESTful API (Part 1 Tutorial) and now Swagger UI will be used only to document the existing API.
Getting Started
- Download the Part 1 source code and open the terminal where you want to save the program
- Run terminal with below command
npm install
npm run start
open browser and run below url
http://localhost:8000/
3. Now, actual magic will start for swagger:
Install Dependencies for swagger
npm i swagger-ui-express -S
4. Create a new file swagger.json at the root
5. Before we start the coding, please refer to the definition and links to get more understanding of the Swagger API definition.
Basic Structure
We will write OpenAPI definitions in JSON. If you are not familiar with the Swagger specification, set of rules that are used to create the Swagger API definition. Kindly follow this link to understand the below definitions. We will guide the basic structure and way to move to create a complex structure.
Here we will learn the Basic structure and CRUD Routes. You will notice below tags
a) The info
the section contains API information: title
, description
(optional), version
:
b) Paths: The paths
the section defines individual endpoints (paths) in your API and the HTTP methods
c) Parameters: Operations can have parameters passed via the URL path (/users/{userId}
), query string (/users?
d) Request Body: If an operation sends a request body, use the requestBody
keyword to describe the body content and media type.
e) Responses: For each operation, you can define possible status codes, such as 200 OK or 404 Not Found, and the response body schema
.
Let’s start coding
5. Open the swagger.json file and add below code
"swagger": "2.0",
"info": {
"version": "1.0.0", //version of the OpenAPI Specification
"title": "My User Project CRUD",
"description": "My User Project Application API",
"license": {
"name": "MIT",
"url": "
}
},
"host": "localhost:8000",
"basePath": "/",
"tags": [
{
"name": "Users",
"description": "API for users in the system"
}
],
"schemes": ["http"],
"consumes": ["application/json"],
"produces": ["application/json"]
}"swagger": "2.0","info": {"version": "1.0.0", //version of the OpenAPI Specification"title": "My User Project CRUD","description": "My User Project Application API","license": {"name": "MIT","url": " https://opensource.org/licenses/MIT },"host": "localhost:8000","basePath": "/","tags": ["name": "Users","description": "API for users in the system"],"schemes": ["http"],"consumes": ["application/json"],"produces": ["application/json"]
6. Open the server.js file and add the below code for swagger integration
const swaggerUi = require(‘swagger-ui-express’),
swaggerDocument = require(‘./swagger.json’);
Also, add the below code before the app.listen code.
app.use(
'/api-docs',
swaggerUi.serve,
swaggerUi.setup(swaggerDocument)
);
7. Now Open the browser with http://localhost:8000/api-docs/
and you will able to see the swagger UI for documentation.
Now we need to create documentation for our existing APIs. As we know we have four API’s CRUD(Create (POST), Read (GET), update (PUT), and delete (Delete).
So we will add Path and definition to our swagger.json file. if you are not familiar with paths and it’s the definition then please refer to this link for more details.
8. We need to add a route on which we will host Swagger UI
a) GET
Open the swagger.json file and add the below code for documentation of API (http://localhost:8000/users)
Reference of swagger.json:
{
"paths": {
"/users": {
"get": {
"tags": ["Users"],
"summary": "Get all users in system",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Users"
}
}
}
}
}
},
"definitions": {
"User": {
"required": ["name", "_id", "companies"],
"properties": {
"_id": {
"type": "integer",
"uniqueItems": true
},
"isPublic": {
"type": "boolean"
},
"name": {
"type": "string"
},
"books": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"amount": {
"type": "number"
}
}
}
},
"companies": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Users": {
"type": "array",
"$ref": "#/definitions/User"
}
}
}
9. Now Open the browser with http://localhost:8000/api-docs/
You will able to see the GET Route documentation based on definition and path:
10. POST
Open the swagger.json file and add the below code for documentation of API (http://localhost:8000/addUser)
Here we will only one more path, as the definition is already defined
{
"paths": {
"/users": {
"get": {
"tags": ["Users"],
"summary": "Get all users in system",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Users"
}
}
}
}
},
"/addUser": {
"post": {
"tags": ["Users"],
"description": "Create new user in system",
"parameters": [
{
"name": "user",
"in": "body",
"description": "User that we want to create",
"schema": {
"$ref": "#/definitions/User"
}
}
],
"produces": ["application/json"],
"responses": {
"200": {
"description": "New user is created",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
}
}
}
11. PUT
Open the swagger.json file and add below code for documentation of API (http://localhost:8000/user/1) (i.e is 1 is dynamic value) and will also modify the route in server.js
Here we will add one more path and a new definition for the update route.
Add one more object under the path as below for PUT
"/user/{id}": {
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "ID of user that we want to find",
"type": "integer"
}
],
"put": {
"summary": "Update user with give ID",
"tags": ["Users"],
"parameters": [
{
"name": "user",
"in": "body",
"description": "User with new values of properties",
"schema": {
"$ref": "#/definitions/updateUser"
}
}
],
"responses": {
"200": {
"description": "User is updated",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
}
Definition for updates
"updateUser": {
"required": ["name", "companies"],
"properties": {
"isPublic": {
"type": "boolean"
},
"name": {
"type": "string"
},
"books": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"amount": {
"type": "number"
}
}
}
},
"companies": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
12. Now Open the browser with http://localhost:8000/api-docs/
you will able to see the PUT Route documentation based on definition and path
13. Delete Path — Open the swagger.json file and add below code for documentation of API (http://localhost:8000/user/1) and we will also update the route in server.js
"delete": {
"summary": "Delete user with given ID",
"tags": ["Users"],
"responses": {
"200": {
"description": "User is deleted",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
Complete source code can be found here.
I hope you will able to understand the flow in a simple way and you can now modify it with the Latest ES6 code and Express js MVC enhanced structure.
Try to convert code to MVC Express js and ES6, you will definitely enjoy 🙂
Conclusion:
This is the explanatory medium story of How to add Swagger UI to existing Node js and Express.js project if you have any doubts, please mail me on [email protected]
Feel free to provide feedback because I am also learning lots of things and it’s not possible to be perfect without sharing knowledge 🙂
Stay Safe and Happy Learning 🙂