Easy!!! RESTful API Documentation with Swagger

Currently, the number of RESRful API applications is increasing. Especially for applications written and used on two platforms: web and mobile. So, one problem is always mentioned: How can we manage those APIs effectively? What are the passed parameters? What data does that API return?

Swagger Editor

The solution would sometimes be: “We need an intermediary to talk between Back-End (API writer) and Frond-End (API user)”. Alternatively, we can use Excel files. It is inconvenient to follow my point. I found out how to tinkle and knew a quite powerful open source to write documentation for that API “Swagger”. So what is it and how is it used, let’s find out together.

What is *** Swagger?

Swagger is an open source software supported by a large ecosystem of tools that help developers, designers, builders, and documenters for RESTful Web Services.

Swagger provides 5 main tools for:

And, the first 3 tools free and 2 tools are the tools that need to be paid if you want to use it. For Swagger Hub, you can create an account here (https://swagger.io/tools/) to be able to experience free for 30 days.

Currently, the need to simply write document APIs for Front-End programmers is essential when the system is too big. Swagger UI has met the minimum requirements for developers and it is being used the most. It helps generate code and generate test cases. In addition, it also allows you to mockup to that API to see the results visually.

The basic structure of a Swagger UI

Every Swagger specification starts with the Swagger version, 2.0 being the latest version. A Swagger version defines the overall structure of an API specification — what you can document and how you document it.

"swagger": "2.0"

Then, you need to specify the API for title, description (optional), version (API version, not file revision or Swagger version).

"info": {
"version": "1.0.0",
"title": "R System",
"description": "This is example from RHP Team about Swagger"
}

Next, The base URL for all API calls are defined using schemes, host and basePath:

"host": "localhost:8888",
"basePath": "/api/v1",
"tags": [
{
"name": "Users",
"description": "API for users in the R System"
}
],
"schemes": [
"http"
]

Next, you will need to define the paths in the API as methods and parameters.
In this part, you need to wrap the outside with a keyword for paths so that the config part understands this is the paths.

  • Paths: Your API (/blogs).
  • Method: API method (get, post, put, delete).
  • Description: Detailed description of your API.
  • Parameters: An array of parameters such as name, schema,...
  • Produces: Return data format (application/json).
  • Response: The return part of the serve. You need to define HTTP code like 200, 404, 500.
"paths": {
"/users": {
"post": {
"tags": [
"Users"
],
"description": "Create new user",
"parameters": [
{
"name": "user",
"in": "body",
"description": "User that we want to create",
"schema": {
"$ref": "#/definitions/User
}
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "User is created!",
"schema": {
"$ref": "#/definitions/Blog"
}
}
}
}
}
}

We need to define a model class for swagger to understand and work properly. In this section, you need to declare the component lock and schemas: the first parameter is Model, then the format part, finally the model properties. In this section, you can define which parameter needs require or not.

"definitions": {
"User": {
"properties": {
"firstName": {
"type": "string",
"uniqueItems": true
},
"lastName": {
"type": "string",
"uniqueItems": true
},
"email": {
"type": "string",
"uniqueItems": true
},
"password": {
"type": "string",
"uniqueItems": true
},
"role": {
"type": "string",
"uniqueItems": false
},
"created": {
"type": "string"
},
"updated": {
"type": "string"
},
"facebook": {
"type": "object"
},
"google": {
"type": "object"
}
},
"required": [
"firstName",
"lastName",
"email",
"password"
]
},
"Users": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}

How to set up the first project with swagger?

In this article, I will guide people to use Swagger with Nodejs.

Step 01: Create a project with npm

npm init -y

Step 02: We need to install some necessary packages to work well with swagger and server.

npm install express body-parser morgan swagger-ui-express

Step 03: Create a swagger.json file and execute the config below

{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "R-SYSTEM",
"description": "system Rhp"
},
"host": "localhost:8888",
"basePath": "/api/v1",
"tags": [
{
"name": "Users",
"description": "API for users in the system"
},
{
"name": "Blogs",
"description": "API for users in the system"
}
],
"schemes": [
"http"
],
"paths": {
"/users": {
"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/Blog"
}
}
}
},
"get": {
"tags": [
"Users"
],
"summary": "Get all users in system",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Users"
}
}
},
"security": [
{
"JWT": []
}
]
}
}
},
"securityDefinitions": {
"JWT": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
},
"definitions": {
"User": {
"properties": {
"firstName": {
"type": "string",
"uniqueItems": true
},
"lastName": {
"type": "string",
"uniqueItems": true
},
"email": {
"type": "string",
"uniqueItems": true
},
"password": {
"type": "string",
"uniqueItems": true
},
"role": {
"type": "string",
"uniqueItems": false
},
"created": {
"type": "string"
},
"updated": {
"type": "string"
},
"facebook": {
"type": "object"
},
"google": {
"type": "object"
}
},
"required": [
"firstName",
"lastName",
"email",
"password"
]
},
"Users": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
},
"consumes": [
"application/json"
],
"produces": [
"application/json"
]
}

Step 04: Create a new server.js to config for the server.

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const config = require('./src/configs/config');
//get all api 
const api = require('./src/routes/index');
//set up the express app 
const app = express();
// log requests to the console
app.use(logger('dev'));
app.use(cors());
// //setup body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/api/v1', api);
app.get('/', (req, res) => res.send(req.ip));
app.use(function (err, req, res, next) {
console.log(err.message);
if (req.app.get('env') !== 'development') {
delete err.stack;
}
res.status(err.statusCode || 500).json(err);
});
module.exports = app;

Note that this file server has been configured to add a router, mongoose, you can create a server file of your choice and add swagger files like my file.

Step 05: Run a serve and go to the link below.

localhost:8888/api-docs

Conclusion

Thus, we found out the basic writing document API Swagger. Hopefully, this article will help your project. Good luck. Enjoy !!!!!

Link Vietnamese article, you can see here.

Author: Quang Le.

Translator: Tran Toan (Sky Albert)