Accelerate Node.js REST API Development with Swagger Codegen: A Step-by-Step Guide

Accelerate Node.js REST API Development with Swagger Codegen: A Step-by-Step Guide

Boost Efficiency and Consistency in Your API Projects by Automatically Generating Server and Client Code from OpenAPI Specifications

·

4 min read

In this article, we will dive into how to generate a node.js REST server and client from an OpenAPI specification. The code presented in this article can be found here: https://github.com/maxshugar/swagger-code-gen-example

What is an OpenAPI Specification?

The OpenAPI Specification (formerly known as Swagger) is a standard for defining RESTful APIs. It allows you to describe the structure of your API so that machines can read them. The specification includes information about endpoints, request/response types, authentication methods, and more. This enables tools to automate API-related tasks, such as generating documentation, code, and tests.

What is Swagger Codegen?

Swagger Codegen is a tool that allows developers to generate client libraries, server stubs, API documentation, and configuration automatically from an OpenAPI Specification. By using this tool, you can quickly create a consistent and standardized setup for your API services and clients, saving significant development time and reducing human error.

Speed

Using Swagger Codegen significantly speeds up the development process by automating the generation of boilerplate code for both servers and clients. This allows developers to focus more on implementing business logic rather than spending time on repetitive tasks.

Step 0: Quick Note on OAS Compatibility

Before we begin, I would just like to note that as of writing (Oct 2024), the latest version of the OpenAPI Specification (OAS) is 3.1.0. This version includes significant improvements, such as full alignment with JSON Schema Draft 2020-12, new support for webhooks, and enhancements in the reuse of components within API specifications. In this project, I’ve used OAS v2 as it is compatible with swagger-codegen, which supports code generation up to OAS version 3. If you are looking for code generation of later versions of OAS, then openapi-generator looks promising.

Step 1: Defining Your Specification

The first step in using Swagger Codegen is to define your API specification in a YAML or JSON format. Below is a simple specification with a single endpoint for retrieving a list of users.

swagger: '2.0'
info:
  title: Sample API
  description: Sample API description.
  version: 1.0.0
host: api.example.com
basePath: /v1
schemes:
  - https
paths:
  /users:
    get:
      summary: Returns a list of users.
      responses:
        200:
          description: A list of users.
          schema:
            type: array
            items:
              $ref: '#/definitions/User'
definitions:
  User:
    type: object
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string

This YAML file defines an API with one endpoint /users that returns a list of users. The response is an array of User objects, each containing an id and a name.

Step 2: Docker Compose

To streamline the process of code generation, we use Docker Compose to set up our environment. Docker Compose allows us to define and run multi-container Docker applications. In this case, we'll use it to run Swagger Codegen in separate containers for generating the server and client code.

Here is the docker-compose.yml file:

version: '3.8'
services:
  swagger_codegen_server:
    image: swaggerapi/swagger-codegen-cli
    volumes:
      - ./src/spec:/local
    command: >
      generate -i /local/spec.yaml
              -l nodejs-server
              -o /local/output-server

  swagger_codegen_client:
    image: swaggerapi/swagger-codegen-cli
    volumes:
      - ./src/spec:/local
    command: >
      generate -i /local/spec.yaml
              -l typescript-fetch
              -o /local/output-client

This file defines two services: swagger_codegen_server and swagger_codegen_client. Both services use the Swagger Codegen CLI Docker image and mount the local directory ./src/spec to the container's /local directory. The generate command specifies the input specification file and the output directories for the generated server and client code. This is not the most efficient approach, as we could create a single container and run these commands sequentially, but will do for now.

Step 3: Generating the Code

To generate the server and client code, you need to start both Docker containers. Run the following command in your terminal:

 docker compose up -d

This command starts the Docker containers in detached mode, allowing them to run in the background. The Swagger Codegen CLI inside the containers reads the specification file and generates the respective server and client code in the specified output directories.

Step 4: Running the server

After generating the server code, navigate to its output directory and install the required dependencies. Then, start the server:

cd spec/output-server
npm i
npm start

This sequence of commands installs the necessary Node.js packages and starts the server on port 8080. You can now interact with the API defined in your specification.

Step 5: Generate Client SDK Requests

With the client code generated, you can create a script to interact with your API. The following script uses the generated TypeScript client to fetch the list of users:

import fetch from 'portable-fetch'; // or your preferred fetch API
import { Configuration, DefaultApi } from '../spec/output-client';

const config = new Configuration({
    basePath: 'http://localhost:8080/v1',
});

const apiInstance = new DefaultApi(config, 'http://localhost:8080/v1', fetch);

// Calling the usersGet method to fetch users
apiInstance
    .usersGet()
    .then((data: any) => {
        console.log('API called successfully. Returned data: ', data);
    })
    .catch((error: any) => {
        console.error(error);
    });

This script configures the client to interact with the server running on http://localhost:8080/v1 and makes a request to the /users endpoint.

Conclusion

Using Swagger Codegen to generate a Node.js server and client from an OpenAPI specification streamlines your API development process. It ensures consistency, reduces boilerplate code, and allows developers to focus on implementing business logic. By following the steps outlined in this article, you can quickly set up your API services and start integrating them into your applications.