API documentation using swagger

ifeanyichima

Ifeanyi Chima

Posted on March 15, 2024

API documentation using swagger

In this article, I will look at how to carry out API documentation. A pre-requisite for this tutorial is fore-hand knowledge of YAML.

When you create an API and you need to explain the API, you can make use of documentation provided by Postman or Swagger

Swagger: This is a tool to generate interactive API documentation.

swagger-jsdoc: To write the specifications.

swagger-ui-express: To serve the swagger UI in our application.

Installation



mkdir server
cd server
npm run init -y
npm i swagger-jsdoc swagger-ui-express


Enter fullscreen mode Exit fullscreen mode

Swagger Options

You need to create options/specifications for swagger ui

  • Give OpenAPI version
  • Give the URL of the server
  • Define the file location of the API route (./route/products)



// doc/swagger.js

import swaggerjsdoc from "swagger-jsdoc"

const options = {
    definition: {
        openapi: "3.0.0",
        info: {
            title: "Products API",
            version: "1.0.0",
            description: 'API Documentation for products API',
            contact: {
                name: 'Chima Ifeanyi',
                email: 'chimaifeanyi29@gmail.com'
            },
        },
        servers: [
            {
                url: "http://localhost:3500/",
            },
        ],
    },
    apis: ["./routes/*.js"],
};

export const swaggerSpecs = swaggerjsdoc(options);



Enter fullscreen mode Exit fullscreen mode

Creating Routes

Your documentation will be written in the file that contains the routes of your API

Schema: You need to create a schema to represent how your data will look like. The schema will be for reusability.

Tags: It is a good idea to group your requests into tags.

Summary: It gives a brief description of the API endpoint.

Parameters: This is to tell swagger that our API request has a parameter in the URL.




// ./routes/routes.js

import express from "express";
export const router = express.Router();

import {productsController} from "../controllers/product.js";


/**
 * @swagger
 * components:
 *  schemas:
 *    Product:
 *     type: object
 *     required: 
 *      - name
 *      - price
 *      - category     
 *     properties:
 *      name:
 *        type: string
 *        description: The product name
 *      price:
 *         type: number
 *         description: The product price
 *      category:
 *          type: string
 *          description: The category
 *     example: 
 *        name: mango
 *        price: 400
 *        category: fruits
 */






/**
 * @swagger
 * tags:
 *  name: Products
 *  description: A products management API
 * 
 */






/**
 * @swagger
 * /home:
 *  get:
 *    summary: returns all the products
 *    tags: [Products]
 *    responses: 
 *      200:
 *        description: A list of all products
 *        content: 
 *          application/json:
 *             schema:
*                 type: array
*                 $ref: "#/components/schemas/Product"
 * 
 * 
 * 
 */

router.get("/", productsController.getProducts);


/**
 * @swagger
 * /home/{name}:
 *  get:
 *      summary: Get product by name
 *      tags: [Products]
 *      parameters:
 *        - in: path
 *          name: name
 *          schema:
 *              type: string
 *          required: true
 *          description: The product name
 *      responses:
 *          200:
 *              description: The product description by name
 *              contents:
 *                  application/json:
 *                      schema:
 *                          $ref: "#/components/schemas/Product"
 *          404:
 *              description: The product was not found
 */

router.get("/:name", productsController.getProductByName);






Enter fullscreen mode Exit fullscreen mode

Image description

It all comes together in our index.js




// src/index.js

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";

import {corsOptions} from "./config/corsOptions.js";
import {connectDB} from "./config/dbConn.js";
import {swaggerSpecs} from "./docs/swagger.js"; // swagger specs
import swaggerui from "swagger-ui-express"; // swagger ui
import swaggerjsdoc from "swagger-jsdoc";


import {router} from "./routes/route.js"


const app = express();

app.use(express.json())


// Connect to MongoDB
connectDB(); 


// middleware to handle url encoded data
app.use(express.urlencoded({ extended: false }));


// built-in middleware for json
app.use(bodyParser.json());


// configuration for cors
app.use(cors(corsOptions));


app.use("/home", router)


// the route for api documentation.
app.use("/api-docs", swaggerui.serve, swaggerui.setup(swaggerSpecs))

app.use('*', (req, res)=>{
    res.status(404).json({ message: 'Endpoint does not exist'})
})


export default app



Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

Thank you, Please follow me

HTML GitHub

💖 💪 🙅 🚩
ifeanyichima
Ifeanyi Chima

Posted on March 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related