Here we will see the best practices for writing Node.js REST APIs. This includes topics such as authentication, naming your routes, black – box testing and also using proper cache headers for these resources. One of the most popular use-cases for Node.js is to write RESTful APIs using it. Let us see practices for writing Node.js REST APIs.



Best practices for Writing Node.js REST APIs from Node Gurus-

1. Use HTTP Methods & API Routes-

You can build a Node.js RESTful API for creating, updating, retrieving or deleting users. For these operations, HTTP has toolset: POST, PUT, GET, PATCH or DELETE.

As a best practice, your API routes should always use nouns as resource identifiers. The routing can be look like:

POST /user or PUT /user:/id to create a new user

GET /user to retrieve a list of users

GET /user/:id to retrieve a user

PATCH /user/:id to modify an existing user record

DELETE /user/:id to remove a user.

2. Use HTTP Status Codes Correctly-

If something wrong with serving a request, you must set the correct status code in the response:

2xx, if everything was okay,

3xx, if the resource was moved,

4xx, if the request cannot be fulfilled because of a client error (like requesting a resource that does not exist),

5xx, if something went wrong on the API side (like an exception happened).

If you are using Express, setting the status code is as easy as res.status(500).send({error: ‘Internal server error happened’}). Similarly with Restify: res.status(201).



3. Choose the right framework for your Node.js REST API-

It is necessary to choose the right framework.

Express, Koa or Hapi- These three are used to create browser applications. They support tempting and also rendering to name a few features. If application needs to provide user-facing side also, it helps for this.

Restify- Restify is focuses to help you for building REST services. It lets you build “strict” API services that can be maintained and observed. Restify also come with automatic DTrace support for all your handlers. For the production of major applications like npm or Netflix, it is useful.

4. Use HTTP headers to send metadata-

To connect metadata about the payload you are going to send, use HTTP headers.

pagination

rate limiting

or authentication

If you require to set any custom metadata in your headers, it will be good to prefix them with x. For eg., if you are using CSRF tokens, it is a general way to name them x-Csrf-Token. Anyway with RFC 6648 they got deprecated. New APIs should try to not utilize header names that can strife with different applications. For eg., OpenStack prefixes its headers with OpenStack.

OpenStack-Identity-Account-ID

OpenStack-Networking-Host-Name

OpenStack-Object-Storage-Policy

Make clear, that the HTTP standard does not define any size limit on the headers. However, Node.js (as of writing this article) imposes an 80KB size limit on the headers object for practical reasons.

5. Black-Box Test your Node.js REST APIs-

It will be the best way to test REST API by treating them as a black box. Black box testing is a testing method where the functionality of an application is analyzed without knowing its internal structure and also working. So none of the dependencies are mocked or stubbed, but the system is tested as a whole. Supertest module can help you with black-box testing Node.js REST API.

A simple test case that checks if a user is returned using the test runner mocha can be implemented like this:

const request = require(‘supertest’)

describe(‘GET /user/:id’, function() {

it(‘returns a user’, function() {

// newer mocha versions accepts promises as well

return request(app)

.get(‘/user’)

.set(‘Accept’, ‘application/json’)

.expect(200, {

id: ‘1’,

name: ‘John Math’

}, done)

})

})



As per your needs, you can populate database with test data with either of the following ways:

Run your black-box test scenarios on a known subset of production data,

Populate the database with crafted data before the test cases are run.

6. Do JWT-Based, Stateless Authentication-

As your REST APIs must be stateless, so does your authentication layer. For this, JWT (JSON Web Token) is ideal.

It consists of 3 parts:

Header, containing the type of the token and the hashing algorithm

Payload, containing the claims

Signature (JWT does not encrypt the payload, just signs it!)

Adding JWT- based authentication to your application is like-

const koa = require(‘koa’)

const jwt = require(‘koa-jwt’)



const app = koa()



app.use(jwt({

secret: ‘very-secret’

}))



// Protected middleware

app.use(function *(){

// content of the token will be available on this.state.user

this.body = {

secret: ’42’

}

})

JWT module does not depend on any database layer. Because all JWT tokens can be verified on their own, and they can also contain time to live values.



7. Conditional requests-

Conditional requests are nothing but the HTTP requests which are executed differently depending on specific HTTP headers. If these requests are met, the requests can be executed in different ways.

These headers attempt to check whether a version of a resource stored on the server matches a given version of the same resource. Hence these headers can be:

the timestamp of the last modification,

or an entity tag, which differs for each version.

These headers are:

Last-Modified (to indicate when the resource was last modified),

Etag (to indicate the entity tag),

If-Modified-Since (used with the Last-Modified header),

If-None-Match (used with the Etag header),

8. Embrace Rate Limiting-

This is used to control how many requests a given consumer can send to the API.

Set the following headers, to tell your API users how many requests they have left:

X-Rate-Limit-Limit, the number of requests allowed in a given time interval

X-Rate-Limit-Remaining, the number of requests remaining in the same interval,

X-Rate-Limit-Reset, the time when the rate limit will be reset.

9. Create a Proper API Documentation-

You write APIs so that others can use them and also take benefit from them. Providing an API documentation for your Node.js REST APIs are crucial.

Below open-source projects can help you with creating documentation for your APIs:

API Blueprint

Swagger

10. Don’t Miss The Future of APIs-

In the previous years, two major query languages for APIs emerged – namely GraphQL from Facebook and Falcor from Netflix. Why these are necessary?

Imagine the following RESTful resource request:

/org/1/space/2/docs/1/collaborators?include=email&page=1&limit=10

This can get out of hand quite easily – as you’d like to get the same response format for all your models all the time. This is where GraphQL and Falcor can help. You can also compare the performance of Node 6 and Node 8 at- Upgrading from Node 6 to Node 8: performance comparison.

Are you looking for a web development to boost your business? Then you are at the right place. Solace expert’s are well trained to use Node.js REST APIs practices for effective development. Get a free quote for web development. We are happy to help you get started through our expert’s.