,

Implement Swagger UI and OpenAPI Contract-Driven Data Validation in TypeScript using Node.js and Express.js

Posted by


⭐ Add Swagger UI and Data Validation from OpenAPI Contract with Node.js + Express.js + TypeScript

Swagger UI is an open-source tool that allows developers to visualize and interact with APIs that use the OpenAPI Specification (formerly known as Swagger) for documenting RESTful web services. It provides a user-friendly interface that allows developers to explore the available endpoints, their input parameters, and expected responses.

Node.js and Express.js are popular frameworks for building server-side applications, while TypeScript is a superset of JavaScript that adds static typing to the language, making it more robust and easier to maintain.

In this tutorial, we will walk through the process of adding Swagger UI and data validation to a Node.js + Express.js + TypeScript project using the OpenAPI contract. This will allow us to document our API endpoints and validate incoming requests against the specified contract.

Step 1: Set up a Node.js + Express.js + TypeScript project

First, let’s set up a basic Node.js + Express.js + TypeScript project. Create a new directory for your project and run the following commands:

$ mkdir swagger-example
$ cd swagger-example
$ npm init -y
$ npm install express typescript ts-node

Create a new file named `index.ts` and add the following code:

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Next, create a TypeScript configuration file named `tsconfig.json` with the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*.ts"]
}

Now, you can start the application by running the command `npx ts-node src/index.ts`. If everything is set up correctly, you should see the message “Server running at http://localhost:3000” in the console.

Step 2: Install and set up Swagger UI

To add Swagger UI to our project, we will use an npm package called `swagger-ui-express`. Install it by running the following command:

$ npm install swagger-ui-express

Create a new file named `swagger.ts` and add the following code:

import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger.json';

const app = express();
const port = 3000;

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(port, () => {
  console.log(`Swagger UI running at http://localhost:${port}/api-docs`);
});

In this code, we are using the `swagger-ui-express` middleware to serve the Swagger UI interface at the `/api-docs` endpoint. The `swaggerDocument` variable refers to a JSON file that contains the OpenAPI contract for our API. We will create this file in the next step.

Step 3: Define the OpenAPI contract

The OpenAPI contract defines the structure of our API, including the available endpoints, their input parameters, and expected responses. Create a new file named `swagger.json` and add the following content:

{
  "openapi": "3.0.0",
  "info": {
    "version": "1.0.0",
    "title": "Swagger Example API",
    "description": "An example API for demonstrating Swagger UI and data validation with Node.js, Express.js, and TypeScript"
  },
  "paths": {
    "/": {
      "get": {
        "summary": "Get a welcome message",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

In this code, we have defined a single endpoint `/` with a GET method. The `responses` section specifies that a successful response with HTTP status code 200 should have a JSON body with a `message` property of type string.

Step 4: Add data validation

To add data validation to our API, we will use an npm package called `express-validator`. Install it by running the following command:

$ npm install express-validator

Update `index.ts` with the following code:

import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
const port = 3000;

app.get('/', [
  body('name').isString().notEmpty(),
], (req, res) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { name } = req.body;
  res.json({ message: `Hello, ${name}!` });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

In this code, we have added data validation to the `/` endpoint using the `express-validator` middleware. The `body(‘name’).isString().notEmpty()` function specifies that the `name` field in the request body should be a non-empty string. If the validation fails, a response with HTTP status code 400 and an array of validation errors is returned. If the validation passes, a response with HTTP status code 200 and a JSON body containing a personalized welcome message is returned.

Step 5: Start the application

Now that everything is set up, you can start the application by running the command `npx ts-node src/swagger.ts`. This will start both the server and the Swagger UI interface.

Open your browser and navigate to `http://localhost:3000/api-docs`. You should see the Swagger UI interface with the available endpoint and their documentation. You can also try sending requests to the API and see the data validation in action.

Congratulations! You have successfully added Swagger UI and data validation from the OpenAPI contract to your Node.js + Express.js + TypeScript project. This will help you document and validate your APIs in a standardized way, making it easier for other developers to understand and interact with your API.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Akshit yadav
1 year ago

very useful video, but i came here for swagger-jsdocs, so try adding some milestones in the video, describing which length belongs to which topic to save the user's time. Thank You!

Luis Neira
1 year ago

Thank you so much for sharing this video. You are very talented. I look forward to more videos from you. Great job!