REST API Boilerplate (Node.js + Express)
A few years ago, I was working with a Raspberry Pi with a Z-Wave adapter to talk to z-wave enabled devices, such as switches, dimmers, and door locks.
I needed a method of keeping track and manipulating user account details, which seemed like the perfect time for me to create something using Node.js + Express.
As REST APIs are a useful and popular type of APIs, I thought I would design a boilerplate that could be re-used to quickly build REST APIs with Node.js + Express.
This REST API boilerplate is available in my Gitlab repo.
Below I will go through the basics of how the boilerplate works, and how it can be used.
The overall idea behind the skeleton was to be very close in nature with how
Ruby on Rails APIs are layed out.
In the root directory of the repository there is a file called route.json, which is a JSON hash that defines the routes for the API which live in the src/resources/ directory.
As an example the default routes.json file contains the following:
"v1/account": {
"routes": [
"/v1/accounts/:id",
"/v1/accounts"
]
},
"v2/account": {
"routes": [
"/v2/accounts/:id",
"/v2/accounts"
]
}
The above, maps out both:
/v1/accounts/:id
/v1/accounts
to the v1/account/
resource in src/api/resources/v1/account.js
(it also maps out a version 2 of a similar API)
src/api/resources/v1/account.js
, has a method per HTTP verb (GET, POST, PUT, DELETE), the breakdown of these methods are:
- index() - GET
- create() - POST
- update() - PUT
- destroy() - DELETE
To handle versioning of the API, each resource in src/api/resources/<version>/
extends an appropriate resource labeled v1.js, v2.js etc.
This particular resource, sets specific things that are related to the particular version, such as a response header: api-version, which tells the caller which version of the API is being used.
The API skeleton includes integration/behavior tests (mocha + chai + chai-http) which live in the test/ directory and can be run using:
npm run test
To run the build process for the API skeleton:
npm run build
To run the API skeleton locally:
npm run start