Document your Express API with Swagger

We all know the importance of documenting your API. As far as Node.js APIs are concerned, whether they're built on Express.js or any other framework, you have plenty of open source options. These include apiDoc, docbox, etc.

In this tutorial, we'll explore using Swagger with the Express.js API. Swagger is a set of open source tools that enable you to design, build, document, and consume RESTful web services. It was created to be nearly agnostic, which means you can use it with almost any language and framework you like.

In our example, how do we turn on the Windows 11 Tamper Protection security feature? Prevent malicious programs from turning off antivirus software We will use two libraries: swagger-ui-express and swagger-jsdoc. The first module allows you to provide Swagger UI (based on swagger-ui project's auto-generated views) from a file or inline object. swagger.json

The second project is about how to use JSDoc throughout the code to improve the download speed of the Android Chrome browser? After setting, the download speed can be increased by 3 times. Annotation integration Swagger. This is useful, especially when you have an extensive API and dozens of models.

Jump ahead:

  • Benefits of Using Swagger

  • Express.js API application setup

  • How to connect Swagger to Node.js

  • Create an API model

    • Integrate actions into routing

    • map endpoint

  • Swagger customization with CSS

Benefits of Using Swagger

Before we get into integrating Swagger into your Node.js application, let's take a look at why Swagger is important for any application - how it can help during the development process.

A significant benefit of Swagger is that it helps to understand how the API works for the client side of the application. Swagger synchronizes the API between the client and server sides of the application. This way, developers working on the front end can understand how the API works and integrate the API to the client side.

Another benefit of using Swagger is that it is comprehensive for developers and non-developers alike. What if everyone involved in product development, including product managers, stakeholders, and developers, can experience slow computer systems? Settings can improve performance and speed up your PC! to try out the API in the UI without running the server standalone.

How can we convert video to AI animation as we like? Real-life video into animation video in seconds Custom API documentation. So, all in all, the main advantage of Swagger is that it makes the API development process faster and more efficient.

Now that we know the advantages of using Swagger in our application, let's look at setting it up and configuring it in our application.

Express.js API application setup

This tutorial won't cover anything related to rapid API builds. We already have a ready-made example that you can clone to your local machine before implementing.

This is a simple API that allows you to manage an in-memory list of books. Feel free to augment it with your customizations.

After installing this feature in your application, run the following command in Terminal:

npm install
npm i swagger-ui-express swagger-jsdoc

These will download the required dependencies into your application. Now it's time to integrate Swagger into your Node.js application.

How to connect Swagger to Node.js

To connect Swagger to the Node.js application, how to set the wifi speed limit of the wireless router? What should I do if there are too many people using the router and the network speed slows down ? Please import and add it in: swagger-ui-express swagger-jsdocserver.js

const express = require("express"),
  bodyParser = require("body-parser"),
  swaggerJsdoc = require("swagger-jsdoc"),
  swaggerUi = require("swagger-ui-express");

These two objects represent the libraries we imported respectively. Next, add the following code before the apply function: listen

const options = {
  definition: {
    openapi: "3.1.0",
    info: {
      title: "LogRocket Express API with Swagger",
      version: "0.1.0",
      description:
        "This is a simple CRUD API application made with Express and documented with Swagger",
      license: {
        name: "MIT",
        url: "https://spdx.org/licenses/MIT.html",
      },
      contact: {
        name: "LogRocket",
        url: "https://logrocket.com",
        email: "[email protected]",
      },
    },
    servers: [
      {
        url: "http://localhost:3000",
      },
    ],
  },
  apis: ["./routes/*.js"],
};
​
const specs = swaggerJsdoc(options);
app.use(
  "/api-docs",
  swaggerUi.serve,
  swaggerUi.setup(specs)
);

As shown in the first line, this configuration object sets OpenAPI to v3.1.0.

Swagger uses the Open API specification, a standard, language-neutral RESTful API interface that allows humans and machines to understand the functionality of web services without accessing source code or inspecting network traffic.

You can refer to the official documentation for all available settings for each version. Here, we only use the basics: API information, name, title, description, license, contact details of the API owner, etc.

The property of the API is essential as it searches for model and endpoint definitions, so inform it properly.

Finally, we use this function to scan the options passed in as parameters and return the transformed Swagger specification object. In turn, this can be used with the setup process. swaggerJsdoc``swaggerUi

You can now start the application via command. You will see the following screen when you visit the URL: npm start `` http://localhost:3000/api-docs/

Note that we still haven't defined any operations in the spec. This happens because we need to explicitly map these actions to routes. Otherwise, Swagger cannot figure out the API endpoints by itself.

(Optional) You can add a search bar to the UI in case the API has too many actions. To do this, change the implementation to the following:

app.use(
  "/api-docs",
  swaggerUi.serve,
  swaggerUi.setup(specs, { explorer: true })
);

The search bar will now display:

Create an API model

As with many important frameworks and API architectures, data is encapsulated into models for easy access. Swagger also expects your API to have models and lets you define them.

Go to and put the following code at the beginning of the file: routes/books.js

/**
 * @swagger
 * components:
 *   schemas:
 *     Book:
 *       type: object
 *       required:
 *         - title
 *         - author
 *         - finished
 *       properties:
 *         id:
 *           type: string
 *           description: The auto-generated id of the book
 *         title:
 *           type: string
 *           description: The title of your book
 *         author:
 *           type: string
 *           description: The book author
 *         finished:
 *           type: boolean
 *           description: Whether you have finished reading the book
 *         createdAt:
 *           type: string
 *           format: date
 *           description: The date the book was added
 *       example:
 *         id: d5fE_asz
 *         title: The New Turing Omnibus
 *         author: Alexander K. Dewdney
 *         finished: false
 *         createdAt: 2020-03-10T04:05:06.157Z
 */

Remember the JSDocs we discussed? JSDocs now comes into play and helps us set up the rest of the Swagger specification definitions through annotations. Here you can define as many schemas as you want. In our case we just define the domain. @swagger``Books

Required Attributes receives a list of attributes that must be filled in the request. This step is critical for letting people know what they must send when using your API.

This property describes details about a model property. Each property must have a name, followed by its type, description (optional), and format (you can also validate the value). See Swagger Data Types for a complete list of available data types. properties

Finally, you can provide an example of request data for this schema model. This will be useful later. When you restart the application and refresh the page, you will see the following screen:

Much better, no?

It's important to note that make sure to check the indentation in your YAML configuration if you encounter in schema: YAMLSemanticError

Integrate actions into routing

Now, we have integrated Swagger into our routes. However, we still have nothing to do. Let's get this out of the way. After the previous JSDoc comment, add the following: schema

/**
 * @swagger
 * tags:
 *   name: Books
 *   description: The books managing API
 * /books:
 *   post:
 *     summary: Create a new book
 *     tags: [Books]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Book'
 *     responses:
 *       200:
 *         description: The created book.
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       500:
 *         description: Some server error
 *
 */

Let's analyze it partly, starting with the Swagger tags. Tags allow you to create a section in your Swagger documentation. All routes assigned to this tag will appear under the same section. This is an organizational environment.

In our example, all endpoints will map to the same tag. Next, we set up our first route: the creation of the book. this is very simple. First, define a and specify the path to which the path will be appended. title``tag

Then, we have requests and responses. In a request, three things are defined: whether the request is required, the content type of the request, and the schema from which the request must be processed.

Schemas can be referenced through Swagger operators. For responses, define the HTTP response codes and the properties for each response code. We're just worried about having .#components/schemas``HTTP 200

Go ahead and test the new action directly in the Swagger UI page:

You can now see where the example values ​​occur. It's easier to provide users with sample data as a reference when they want to perform actions.

You can find code for all other operations below:

/**
 * @swagger
 * tags:
 *   name: Books
 *   description: The books managing API
 * /books:
 *   get:
 *     summary: Lists all the books
 *     tags: [Books]
 *     responses:
 *       200:
 *         description: The list of the books
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Book'
 *   post:
 *     summary: Create a new book
 *     tags: [Books]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Book'
 *     responses:
 *       200:
 *         description: The created book.
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       500:
 *         description: Some server error
 * /books/{id}:
 *   get:
 *     summary: Get the book by id
 *     tags: [Books]
 *     parameters:
 *       - in: path
 *         name: id
 *         schema:
 *           type: string
 *         required: true
 *         description: The book id
 *     responses:
 *       200:
 *         description: The book response by id
 *         contens:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       404:
 *         description: The book was not found
 *   put:
 *    summary: Update the book by the id
 *    tags: [Books]
 *    parameters:
 *      - in: path
 *        name: id
 *        schema:
 *          type: string
 *        required: true
 *        description: The book id
 *    requestBody:
 *      required: true
 *      content:
 *        application/json:
 *          schema:
 *            $ref: '#/components/schemas/Book'
 *    responses:
 *      200:
 *        description: The book was updated
 *        content:
 *          application/json:
 *            schema:
 *              $ref: '#/components/schemas/Book'
 *      404:
 *        description: The book was not found
 *      500:
 *        description: Some error happened
 *   delete:
 *     summary: Remove the book by id
 *     tags: [Books]
 *     parameters:
 *       - in: path
 *         name: id
 *         schema:
 *           type: string
 *         required: true
 *         description: The book id
 *
 *     responses:
 *       200:
 *         description: The book was deleted
 *       404:
 *         description: The book was not found
 */

Ideally, these mappings should be placed above each Express.js routing function. However, for simplicity, we've gathered them all in one place.

map endpoint

We now divide operations into two main categories: those that take arguments and those that don't. This is necessary for Swagger to know how to match routes with the correct path parameters. id

Whenever there is a parameter in the endpoint, regardless of its type, the details under the property must be notified. parameters

Here is the result of correctly mapping all endpoints:

Swagger customization with CSS

You can customize the Swagger UI by implementing custom CSS in the Swagger integration. To do this, add the option to: customCssUrl``swaggerUi.setup

app.use(
  "/api-docs",
  swaggerUi.serve,
  swaggerUi.setup(specs, {
    explorer: true,
    customCssUrl:
      "https://cdn.jsdelivr.net/npm/[email protected]/themes/3.x/theme-newspaper.css",
  })
);

Here we pass a custom CSS file to options. It will change Swagger UI with custom styles. customCssUrl

Here's what it looked like before the custom CSS file:

Now, see what it looks like after:

in conclusion

You can test each endpoint individually to make sure it works exactly as your Postman request does.

Swagger can do more than just document your API. A quick read of the official documentation will give you a better idea of ​​what it does. Remember that documentation should be part of the team culture. Otherwise, your documentation will not always be up to date.

Guess you like

Origin blog.csdn.net/weixin_47967031/article/details/132639571