Featured image of post Code-First OpenAPIs with Node.js

Code-First OpenAPIs with Node.js

For Fun and Profit


๐ŸŽฏ What is Code-First API Development?

In a nutshell, code-first means you build your API in actual code (JavaScript/TypeScript) and generate an OpenAPI specification from it automatically.

This is way cooler than writing a massive YAML file by hand.

With this approach, you get:

  • Self-documenting APIs ๐Ÿ“–
  • Fewer human errors (because who likes debugging indentation in YAML?)
  • Automatic validation and type checking
  • An easy-to-maintain API spec

๐Ÿ› ๏ธ What Weโ€™re Using

Weโ€™re going to use:

๐Ÿš€ Setting Up the Project

First things first, letโ€™s create a new Node.js project:

1
2
mkdir openapi-code-first && cd openapi-code-first
npm init -y

Now, install the required dependencies:

1
npm install express swagger-jsdoc swagger-ui-express

๐Ÿ—๏ธ Creating an Express Server

Letโ€™s start with a basic Express server (server.js):

1
2
3
4
5
6
7
8
9
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

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

Run it with:

1
node server.js

Boom!

You have a running server.

Not impressed?

Hold my coffee. โ˜•


๐Ÿ“œ Defining the OpenAPI Spec with swagger-jsdoc

Now, letโ€™s generate an OpenAPI spec using swagger-jsdoc.

We add comments above our routes and let the magic happen.

First, create a new file swaggerConfig.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const swaggerJSDoc = require('swagger-jsdoc');

const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Awesome API',
version: '1.0.0',
},
},
apis: ['./server.js'], // Path to API docs
};

const swaggerSpec = swaggerJSDoc(options);
module.exports = swaggerSpec;

Now, update server.js to serve the docs:

1
2
3
4
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swaggerConfig');

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

Visit http://localhost:3000/api-docs and behold the glory of a fully documented API! ๐ŸŽ‰


โœจ Adding Routes with OpenAPI Annotations

Letโ€™s add an actual API endpoint with OpenAPI documentation.

Modify server.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/**
* @swagger
* /hello:
*   get:
*     summary: Returns a greeting
*     responses:
*       200:
*         description: A friendly greeting
*/
app.get('/hello', (req, res) => {
res.json({ message: 'Hello, world!' });
});

Now, restart your server and check http://localhost:3000/api-docs again.

Youโ€™ll see your GET /hello endpoint fully documented.

Neat, huh?


๐Ÿ—๏ธ Adding Parameters and Responses

Letโ€™s level up and add route parameters and response definitions.

Modify server.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
* @swagger
* /greet/{name}:
*   get:
*     summary: Greet a user
*     parameters:
*       - name: name
*         in: path
*         required: true
*         schema:
*           type: string
*     responses:
*       200:
*         description: A personalized greeting
*/
app.get('/greet/:name', (req, res) => {
res.json({ message: `Hello, ${req.params.name}!` });
});

Now, go to http://localhost:3000/api-docs and test your new personalized greeting API! ๐ŸŽ‰


๐Ÿ”ฅ Wrapping Up

Hereโ€™s what we did:

  • Set up an Express.js server
  • Used swagger-jsdoc to generate OpenAPI specs
  • Documented routes directly in JSDoc comments
  • Served the docs using swagger-ui-express

๐Ÿ—๏ธ Key Ideas

Key IdeaSummary
Code-First API DevelopmentGenerate OpenAPI specs directly from code
swagger-jsdocConverts JSDoc comments into OpenAPI docs
swagger-ui-expressServes the docs in a web UI
Express.jsSimple Node.js web framework
OpenAPIStandard for REST API documentation

๐Ÿ“š References