Swagger based Routing in Node JS/Express API
Traditionally, express comes with a router which can be used to define routes in your API.
A typical routes file looks like:
app.get('/books/:id', booksController.getBook)
app.post('/books', booksController.createBook)
...
Swagger is the de-facto language for API documentation. Swagger uses the Open API spec to describe the API definitions.
Here in this article, I am going to talk about how to use Swagger which is an API documentation tool and connect it with Express API routes. This has the following benefits:
- You don’t have to explicitly define your routes anymore, they are defined using the swagger definition you have created for your APIs.
- You can have certain middlewares that work on this API definition to do tasks like translation, id-lookup (which we will get to in the next articles)
Let’s get started.
Packages
We will use the below 2 npm packages:
- swagger-routes-express — For connecting the swagger api definitions to express routes
- swagger-ui-express — For displaying the API definitions on web
Use npm install
to install these dependencies
Steps
- Import the libraries in
app.js
2. Create api.yaml
file for our swagger definitions
Here we have referenced another yaml books.yaml
under schemas
directory which contains all the API definitions for books.
This is for modularity, and also preventing api.yaml
file from getting large.
3. Load the swagger definition file
I am using a helper function to load swagger definitions as I have referenced books.yaml
within my api.yaml
4. Create routes.js
file to map the operationId
in swagger to express handler.
5. Finally, connect swagger to express and host your api definitions on /docs
path in express
You can now go to http://localhost:8082/docs to access your API definitions. (8082 is the port I use on local development, change this to the port you have started your app on)
So there we have it — a working express routes with API definitions in swagger!