Bipon Biswas
Posted on July 9, 2023
Objective: In this article, you will know how to Create NodeJS server, Connect swagger
Pre-requisite Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node.
First step: Init for project starting
npm init -y
Then install for other plugin
npm i express swagger-ui-express yamljs
Also install for Dev dependency
npm i -D nodemon
Configure package.json
file
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
Create a index.js
file and Import necessary plugin which already installed.
const express = require('express')
const swaggerUI = require('swagger-ui-express')
const YAML = require('yamljs')
const swaggerDoc = YAML.load('./swagger.yaml')
Create express server and config few thing into index.js
file
//express app
const app = express()
app.use(express.json())
app.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerDoc))
app.get('/health', (_req, res) => {
res.status(200).json({
health: 'Ok'
})
})
app.listen(4000, ()=> {
console.log('Server is listening on port 4000')
} )
Create swagger.yaml
file. Where insert this basic file.
openapi: 3.0.0
info:
version: 1.0.0
title: Testing Open Api Spec
description: >
I am learning Open API Specification. This is industry standard specification technique for any web service
termsOfService: https://example.com/terms
contact:
name: Bipon Biswas
url: https://example.com
email: support@gmail.com
license:
name: Apache 2.0
url: http://apache.com
servers:
- url: http://localhost:4000/api/v1
description: dev server
- url: http://example.com/api/v1
description: prod server
paths:
/health:
get:
tags: [Health]
description: this endpoint will test the health of the api
responses:
'200':
description: it will return a success message
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: ok
'500':
description: The Server is down
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: server is down
Now run the project
npm run dev
Now hit the URL into browser http://localhost:4000/health
Also hit the URL http://localhost:4000/docs/
Reference
Posted on July 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.