How To Integrate Swagger With Express JS

Krishna KV
Technology Specialist
July 25, 2018
Rate this article
[Total: 3    Average: 3.7/5]
Views    373

Swagger is a framework that helps us to describe API endpoints in a common language that everyone can understand. Swagger spec also helps to test and validate API by providing necessary UI elements that are required to submit data to API endpoints. This article explains how to create a swagger spec docs for a TypeScript based Express Js Application.

The below are some of the advantages of having Swagger integrated to an API

  • It can be called as a blueprint of the API.
  • Explains API parameters and the return response
  • Lists all operations that your API supports
  • It helps us to debug and test the API.

Swagger Documentation
The swagger documentation can be written in JS, Yaml or JSON and it is compared against the Swagger Spec.
Swagger UI
Swagger UI was the first tool which offers the API documentation into interactive documentation for test client. Methods can be expanded with description and information related to parameters, which helps to execute API endpoints and view the response of the API.

In this example we are using the JSON Documentation.

Let’s starting the swagger documentation for the previous API CRUD operation.
Add the package.
"swagger-ui-express": "3.0.10

Add a folder name swagger-docs and add the below customer.swagger.json.

{
    "swagger": "2.0",
    "info": {
        "title": "Customer",
        "description": "",
        "version": "1.0"
    },
    "produces": [
        "application/json"
    ],
    "tags": [
        {
            "name": "Customer",
            "description": ""
        }
    ],
    "host": "",
    "basePath": "/Customers",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "customer"
                ],
                "description": "Display all the customers",
                "responses": {
                    "400": {
                        "description": "Invalid input"
                    },
                    "200": {
                        "description": "Success"
                    }
                }
            },
            "post": {
                "tags": [
                    "customer"
                ],
                "description": "Add a new customer",
                "consumes": [
                    "application/json"
                ],
                "produces": [
                    "application/json"
                ],
                "required": true,
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "Payload for adding new",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/customer"
                        }
                    }
                ],
                "responses": {
                    "400": {
                        "description": "Invalid input"
                    },
                    "200": {
                        "description": "Success"
                    }
                }
            },
            "put": {
                "tags": [
                    "customer"
                ],
                "description": "Update an existing customer",
                "required": true,
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "To add a update a customer, provide the existing Id",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/customer"
                        }
                    }
                ],
                "responses": {
                    "400": {
                        "description": "Invalid input"
                    },
                    "200": {
                        "description": "Success"
                    }
                }
            }
        },
        "/{id}": {
            "get": {
                "tags": [
                    "Customer"
                ],
                "description": "Get customer by Id",
                "consumes": [
                    "application/json"
                ],
                "produces": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "id",
                        "in": "path",
                        "required": true,
                        "type": "number"
                    }
                ],
                "responses": {
                    "400": {
                        "description": "Invalid input"
                    },
                    "200": {
                        "description": "Success"
                    }
                }
            },
            "delete": {
                "tags": [
                    "Customer"
                ],
                "description": "Delete a customer by Id",
                "parameters": [
                    {
                        "name": "id",
                        "in": "path",
                        "required": true,
                        "type": "number"
                    }
                ],
                "responses": {
                    "400": {
                        "description": "Invalid input"
                    },
                    "200": {
                        "description": "Success"
                    }
                }
            }
        }
    },
    "definitions": {
        "customer": {
            "type": "object",
            "properties": {
                "Id": {
                    "type": "number",
                    "format": "int64"
                },
                "Name": {
                    "type": "string"
                },
                "Address": {
                    "type": "string"
                }
            }
        }
    }
}

Add swagger.controller.ts inside the controller folder.

import { Router, Request, Response, NextFunction, Express } from 'express';
import { AppSetting } from './../config';
const swaggerUi = require('swagger-ui-express');
import * as customer from '../swagger-docs/customer.swagger.json';

export class SwaggerController {
    public static route = '/swagger';

    public static configure(app: Express) {
        app.use('/swagger/customer', swaggerUi.serve, swaggerUi.setup(customer));
    }
}

app.use(routeurl,middleware for swagger,Swagger document)

Add the swagger middleware in express.api.ts

private configureRoutes() {
        this.app.use(function (req: Request, res: Response, next: NextFunction) {
            for (let key in req.query) {
                if (key) {
                    req.query[key.toLowerCase()] = req.query[key];
                }
            }
            next();
        });

        ApiRouting.ConfigureRouters(this.app);
        SwaggerController.configure(this.app);
    }

To test the swagger

Open browser and navigate to  http://localhost:40401/swagger/customer

Swagger

Click here for Download/clone the project from github

Subscribe To Our Newsletter

Leave a comment