Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenAPI Generator - JavaScript Example

📌 Introduction

This project is a simple example of how OpenAPI Generator can be used with a Node.js and Express.js API.

The main purpose of this project is to understand how OpenAPI Generator works.

The project demonstrates:

Express API
     ↓
OpenAPI Specification
     ↓
OpenAPI Generator
     ↓
Generated JavaScript Client

📖 What is OpenAPI?

OpenAPI is a specification used to describe REST APIs.

It describes:

  • API endpoints
  • HTTP methods
  • Parameters
  • Request body
  • Response
  • Data models
  • API information

For example:

GET    /users
POST   /users
GET    /users/{id}

These APIs are described inside:

openapi/openapi.yaml

The OpenAPI file works like a blueprint or contract for the API.


⚙️ What is OpenAPI Generator?

OpenAPI Generator is a tool that reads an OpenAPI specification and generates code from it.

In this project, we use the JavaScript generator.

The basic idea is:

openapi.yaml
     ↓
OpenAPI Generator
     ↓
JavaScript Generator
     ↓
Generated JavaScript Client

Instead of manually writing repetitive API client code, the OpenAPI specification can be used to generate that code automatically.


🎯 Purpose of This Project

The purpose of this project is to understand:

  1. How to create a simple Express API.
  2. How to describe that API using OpenAPI.
  3. How to validate the OpenAPI specification.
  4. How OpenAPI Generator reads the specification.
  5. How the JavaScript generator is selected.
  6. How templates are used to generate JavaScript code.
  7. Where the generated files are created.

📂 Project Structure

Before running the generator:

openapi-generator-demo/
│
├── server/
│   └── server.js
│
├── openapi/
│   └── openapi.yaml
│
├── package.json
└── package-lock.json

After running the JavaScript generator:

openapi-generator-demo/
│
├── server/
│   └── server.js
│
├── openapi/
│   └── openapi.yaml
│
├── generated/
│   └── Generated JavaScript Files
│
├── package.json
└── package-lock.json

The generated folder is created by OpenAPI Generator. It does not need to be created manually.


🏗️ Step 1 - Create Express API

The Express server is located at:

server/server.js

Example:

const express = require("express");

const app = express();

app.use(express.json());


// GET all users
app.get("/users", (req, res) => {

    const users = [
        {
            id: 1,
            name: "Srinivas",
            email: "srinivas@example.com"
        },
        {
            id: 2,
            name: "Ravi",
            email: "ravi@example.com"
        }
    ];

    res.json(users);
});


// GET user by ID
app.get("/users/:id", (req, res) => {

    const id = Number(req.params.id);

    const user = {
        id: id,
        name: "Srinivas",
        email: "srinivas@example.com"
    };

    res.json(user);
});


// Create user
app.post("/users", (req, res) => {

    const user = {
        id: 3,
        name: req.body.name,
        email: req.body.email
    };

    res.status(201).json(user);
});


const PORT = 3000;

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

▶️ Step 2 - Run the Express Server

Run:

node .\server\server.js

Expected output:

Server running on http://localhost:3000

Now open:

http://localhost:3000/users

The API should return the users.


📄 Step 3 - Create OpenAPI Specification

Create:

openapi/openapi.yaml

The OpenAPI file describes the APIs created in the Express server.

Example:

openapi: 3.0.3

info:

  title: User API

  version: 1.0.0

  description: Simple User Management API


servers:

  - url: http://localhost:3000


paths:

  /users:

    get:

      operationId: getUsers

      summary: Get all users

      responses:

        "200":

          description: Successfully retrieved users

          content:

            application/json:

              schema:

                type: array

                items:

                  $ref: "#/components/schemas/User"


components:

  schemas:

    User:

      type: object

      properties:

        id:
          type: integer

        name:
          type: string

        email:
          type: string

🔍 Step 4 - Validate OpenAPI Specification

Before generating code, validate the OpenAPI file.

Run:

npx @openapitools/openapi-generator-cli validate -i openapi/openapi.yaml

This checks whether the OpenAPI specification is valid.

The flow is:

openapi.yaml
     ↓
Validator
     ↓
Valid OpenAPI Specification

⚙️ Step 5 - Generate JavaScript

Run:

npx @openapitools/openapi-generator-cli generate -i openapi/openapi.yaml -g javascript -o generated

The command contains three important options.

-i

-i openapi/openapi.yaml

Means:

Use openapi.yaml as the input.

-g

-g javascript

Means:

Use the JavaScript generator.

-o

-o generated

Means:

Put the generated files inside the generated directory.


🔄 How OpenAPI Generator Works

The internal process can be understood as:

             openapi.yaml
                  │
                  ▼
             Read / Parse
                  │
                  ▼
         Understand API Structure
                  │
                  ▼
          Internal API Model
                  │
                  ▼
        Select JavaScript Generator
                  │
                  ▼
              Templates
                  │
                  ▼
       Insert API Information
                  │
                  ▼
          Generate JavaScript
                  │
                  ▼
             generated/

🧩 What Does the Generator Read?

From the OpenAPI file, the generator understands:

API Path

/users:

It understands:

Path = /users

HTTP Method

get:

It understands:

Method = GET

Operation ID

operationId: getUsers

It understands:

Operation = getUsers

Parameters

For:

/users/{id}

it understands that id is a path parameter.

Response

For:

"200":

it understands that the successful response uses HTTP status 200.

Model

For:

User:

it understands that User is a data model.


🧠 How Does Code Generation Work?

OpenAPI Generator uses templates to create the output.

Conceptually, a template may contain:

function {{operationId}}() {

    // API request

}

The OpenAPI specification provides:

operationId = getUsers

The generator combines the API information with the template.

Conceptually:

Template
    +
OpenAPI Information
    ↓
Generated JavaScript

The actual generated files contain more complete code depending on the selected generator.


📦 Generated Folder

After running:

npx @openapitools/openapi-generator-cli generate -i openapi/openapi.yaml -g javascript -o generated

OpenAPI Generator creates the output directory.

The generated structure can vary depending on the generator and version, but it will contain JavaScript client files and supporting files.

For example:

generated/
│
├── src/
│   ├── api/
│   ├── model/
│   └── ...
│
├── package.json
├── README.md
└── ...

🔑 Important Concept

There are two different things in this project.

Express Server

server/server.js

This contains the actual API implementation.

It tells the application:

HOW the API works.

OpenAPI Specification

openapi/openapi.yaml

This describes:

WHAT the API looks like.

It describes:

  • Endpoint
  • Method
  • Parameters
  • Request
  • Response
  • Models

🔄 Complete Project Flow

                    Express Server
                         │
                         ▼
                      REST API
                         │
                  API Description
                         │
                         ▼
                    openapi.yaml
                         │
                         ▼
                OpenAPI Generator
                         │
                         ▼
                JavaScript Generator
                         │
                         ▼
                     Templates
                         │
                         ▼
              Generated JavaScript
                         │
                         ▼
                    generated/

🧪 Commands Used

Install Express

npm install express

Install OpenAPI Generator

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

Check Java

java -version

Check OpenAPI Generator

npx @openapitools/openapi-generator-cli version

Run Express Server

node .\server\server.js

Validate OpenAPI

npx @openapitools/openapi-generator-cli validate -i openapi/openapi.yaml

Generate JavaScript

npx @openapitools/openapi-generator-cli generate -i openapi/openapi.yaml -g javascript -o generated

⚠️ Important Note About Java

OpenAPI Generator uses Java internally.

Therefore, Java must be installed even though this project generates JavaScript.

The flow is:

Java
  ↓
Runs OpenAPI Generator
  ↓
JavaScript Generator
  ↓
JavaScript Output

Java is only required to run the generator. The generated application/client is JavaScript.


💡 Why Use OpenAPI Generator?

Without OpenAPI Generator:

Developer
    ↓
Manually write API client
    ↓
Manually write models
    ↓
Manually maintain API methods

With OpenAPI Generator:

OpenAPI Specification
       ↓
OpenAPI Generator
       ↓
Generated JavaScript Client

This can reduce repetitive development work and keep generated API client code aligned with the API specification.


🎯 Key Takeaway

The main concept of this project is:

OpenAPI = API Blueprint

OpenAPI Generator = Code Generation Tool

JavaScript Generator = Generates JavaScript

Generated Folder = Generated Output

In one sentence:

OpenAPI Generator reads the API definition from openapi.yaml, converts the API information into an internal model, applies the selected JavaScript generator and its templates, and generates JavaScript client files automatically.


👨‍💻 What This Project Demonstrates

This project demonstrates:

  • Creating a REST API using Express.js
  • Creating an OpenAPI specification
  • Validating an OpenAPI specification
  • Installing OpenAPI Generator
  • Selecting the JavaScript generator
  • Generating JavaScript client code
  • Understanding the generator and template process
  • Understanding the difference between an API implementation and an API specification

📚 Official Documentation

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages