Automating API Code with OpenAPI Generator in Node.js Projects: Setup and Configuration Guide

0

In Node.js projects, there’s a need for a tool that can automate API documentation and efficiently generate client and server code. OpenAPI Generator is a powerful tool that meets these requirements. In this article, we will delve into how to set up and use OpenAPI Generator using `openapi.json` and `openapitools.json` files.

What is OpenAPI Generator?

OpenAPI Generator is a tool that automatically generates client and server code for various languages and frameworks based on the OpenAPI (Swagger) specification. It helps efficiently manage the API development and documentation process.

1. Installing OpenAPI Generator

First, install OpenAPI Generator. You can use `npm` or `yarn` in a Node.js environment.

npm install @openapitools/openapi-generator-cli -g

or

yarn global add @openapitools/openapi-generator-cli

2. Preparing the OpenAPI Specification File

Prepare an OpenAPI specification file (`openapi.yaml` or `openapi.json`) for API documentation. This file should define the API endpoints, request and response formats, and models.

Example `openapi.yaml` file

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string

3. Configuring the `openapi.json` File

Create an `openapi.json` file in the project’s root directory. This file defines the structure of the code generated by OpenAPI Generator.

{
	"modelPackage": "src/model",
	"apiPackage": "api",
	"withSeparateModelAndApi": true
}
  • modelPackage: Directory for API model definition files
  • apiPackage: Directory for API endpoint handler files
  • withSeparateModelAndApi: Generate separate directories for models and APIs

4. Configuring the `openapitools.json` File

An `openapitools.json` file is also needed to configure the OpenAPI Generator CLI.

{
	"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
	"spaces": 2,
	"generator-cli": {
		"version": "6.2.0"
	},
	"enumPropertyNaming": "original"
}
  • $schema:@b] Path to the JSON schema file
  • spaces:@b] Number of spaces for indentation
  • generator-cli:@b] Version of OpenAPI Generator CLI to use
  • enumPropertyNaming:@b] Naming convention for enum properties

5. Generating Code

Generate the code using OpenAPI Generator.

openapi-generator-cli generate -i openapi.yaml -g nodejs-express-server -o ./generated --config openapi.json
  • -i: Path to the input file (OpenAPI specification file)
  • -g: Type of code generator (`nodejs-express-server`)
  • -o: Output directory
  • –config: Additional configuration file (`openapi.json`)

6. Using the Generated Code

The generated code will be located in the `./generated` directory. You can integrate this code into your project.

Example of running an Express server:

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

// Include generated API routes
const apiRoutes = require('./generated/api');

app.use('/api', apiRoutes);

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

Conclusion

Using OpenAPI Generator allows you to efficiently manage the API development and documentation process. Properly setting up `openapi.json` and `openapitools.json` files enables you to automate code generation tailored to your project’s needs. This can save development time and enhance the consistency and maintainability of your code.

Understanding and applying OpenAPI Generator in Node.js projects can significantly improve the efficiency of API development and management. Follow this guide to install and configure OpenAPI Generator to start automating your API code today.

Leave a Reply