Ten best practices of node.js rest API

Jiedao jdon 2021-05-03 20:51:18
best practices node.js node js

In this paper , We're going to talk about writing Node.js REST API Best practices , Including named routes , Authentication , Topics like black box testing and using appropriate cache headers for these resources .

#1 - Use HTTP Methods and API route

Imagine , You are building a Node.js RESTful API, Used to create , to update , Retrieve or delete users . For these operations HTTP There are already enough toolsets :POST,PUT,GET,PATCH or DELETE.

As best practice ,API Routing should always use nouns as resource identifiers . For example, user resources , The route might look like this :

POST /user perhaps PUT /user:/id Create a new user ,

GET /user Retrieve the list of users ,

GET /user/:id Retrieve users ,

PATCH /user/:id Modify existing user records ,

DELETE /user/:id Delete user

“API Routing should always use nouns as resource identifiers !”

#2 - Use... Correctly HTTP The status code

If there is a problem providing the request , You must set the correct status code for it in the response :

2xx everything goes well ,

3xx, Resources are moved ,

4xx, Due to a client error ( Such as requesting a non-existent resource ) And can't satisfy the request ,

5xx,API There's something wrong with ( It's like something's going wrong ).

If you use Express, Setting the status code is like res.status(500).send({error: 'Internal server error happened'}).

Restify be similar :res.status(201).

#3 - Use HTTP Mark and send metadata

To attach metadata about payload content to be sent , Please use HTTP header . Titles like this can be the following information :

Pagination ,

The speed limit ,

Or certification .

Can be in here Find Standardization HTTP A list of headers

If you need to set any... In the title ​​ How to customize metadata , The best way is to prefix them X. for example , If you are using CSRF token , So name them common ( But it's not standard ) The way X-Csrf-Token. However , about RFC 6648, They have been abandoned . new API Best efforts should be made not to use header names that may conflict with other applications . for example ,OpenStack Prefix its header OpenStack:




Please note that ,HTTP The standard does not define any size limit for the header ; however , For practical reasons ,Node.js( At the time of writing ) Put... On the head object 80KB Size limit for .

“ Don't allow HTTP header ( Include status lines ) The total size of is more than HTTP_MAX_HEADER_SIZE. This check is used to protect the embedder from denial of service attacks “.

come from Node.js HTTP Parser

#4 - by Node.js REST API Choose the right framework

It's important to choose the framework that best suits the use case .

Express,Koa or Hapi

Express,Koa and Hapi Can be used to create browser applications , They also support templates and rendering .


On the other hand ,Restify Focus on helping you build REST service . It exists to allow you to build maintainable and observable “ Strictly ”API service .Restify It also provides automatic DTrace Support .

Restify For major applications ( Such as npm or Netflix) In production .

“Restify It's there for you to build maintainable and observable ” Strictly “API service .”

#5 - Black box test your Node.js REST API

test REST API One of the best ways to do this is to think of them as black boxes .

Black box testing is a way to test the function of an application , No need to understand its internal structure or working principle . therefore , No dependencies are simulated or stub , But the system is tested as a whole .

One of them can help you with black box testing Node.js REST API The best modules are .

Check whether the user is using the test runner mocha The simple test cases returned can be implemented in this way :

const request = require('supertest')
describe('GET /user/:id', function() {
it('returns a user', function() {
// newer mocha versions accepts promises as well
return request(app)
.set('Accept', 'application/json')
.expect(200, {
id: '1',
name: 'John Math'
}, done)

You may ask : How to fill in the data for REST API In the database that provides the service ?

Generally speaking , It's a good way to write tests in such a way that there are as few assumptions about the state of the system as possible . You can use one of the following methods to fill the database with test data :

Run the black box test scenario on a known subset of production data ,

Before running the test case , Filling the database with well-designed data .

Of course , Black box testing doesn't mean you don't have to do unit testing , You still need to work for your API Write unit tests .

#6 - be based on JWT The stateless authentication of

because REST API It has to be stateless , So it's the same with the authentication layer . So ,JWT (JSON Web Token) It's the ideal choice .

JWT It's made up of three parts :

header , Contains token type and hash algorithm

Payload payload, Include declaration definitions

Signature ,(JWT No payload encryption , Just sign !)

Will be based on JWT It's very easy to add authentication to your application :

const koa = require('koa')
const jwt = require('koa-jwt')
const app = koa()
secret: 'very-secret'
// Protected middleware
app.use(function *(){
// content of the token will be available on this.state.user
this.body = {
secret: '42'

To access the protected endpoint above , Must be in Authorization The token is provided in the header field .

curl --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" my-website.com

Be careful JWT The module does not depend on any database tier . Because all JWT The token can be verified by itself , And they can also contain lifetime values .

Besides , Always make sure that only by using HTTPS Secure connection to access all API Endpoint .

#7 - Use conditional request

The condition request is HTTP The request is based on a specific HTTP The header performs different HTTP request . You can think of these headers as prerequisites : If these headers are met , The request will be executed in different ways .

According to the specific HTTP The header performs different conditional requests

<p class="click-to-tweet-button">
<a href="https://twitter.com/share?text=%22Conditional%20requests%20are%20executed%20differently%20depending%20on%20specific%20HTTP%20headers%22%20via%20%40RisingStack;url=https://blog.risingstack.com/10-best-practices-for-writing-node-js-rest-apis" target="_blank" c>Click To Tweet</a>

These headers attempt to check whether the version of the resource stored on the server matches the specified version of the same resource . For this reason , These titles can be :

The last modified timestamp ,

Or entity labels , Each version is different .

These titles can be :

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

Etag ( Represents an entity label ),

If-Modified-Since ( And Last-Modified Use the title together ),

If-None-Match ( And Etag Use the title together ),

#8 - Embrace speed limits

The rate limit is used to control that a specified consumer can send to API Number of requests sent .

To tell you API How many requests do users have left , Please set the following header :

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 that the rate limit will be reset .

majority HTTP Frameworks support out of the box ( Or use plug-ins ). for example , If you use Koa, Then there are koa-ratelimit package .

Please note that , The time window may vary depending on API Different providers - for example ,GitHub Use it for an hour , and Twitter Then for 15 minute .

#9 - Create the right API file

To write API Documents so that others can use them , Benefit from . by Node.js REST API Provide API Documentation is essential .

Here are two open source projects that can help you API create documents :

API The blueprint


#10 - Don't miss API The future of

In the last few years , There are two main kinds of API query language - From Facebook Of GraphQL And from the Netflix Of Falcor. Why do we need them ?

Imagine RESTful Resource request :


It's easy to get out of control - Because you want to always get the same response format for all models . This is it. GraphQL and Falcor Where you can help .

GraphQL yes API Query language of , Use existing data to complete these queries .GraphQL Provides API A complete and easy to understand description of data in , Enable customers to ask exactly what they need , That's it , send API It's easier to develop over time , And support powerful developer tools .

About Falcor

Falcor Is for Netflix Innovative data platform supported by user interface .Falcor Allows you to model all back-end data as a single... On a node server Virtual JSON object . On the client , You can use the familiar JavaScript operation ( Such as get,set and call) To handle remote JSON object . If you know your data , You'll know your own API.

original text

本文为[Jiedao jdon]所创,转载请带上原文链接,感谢

  1. Analysis of MVC
  2. [middle stage] please stay and join me in the backstage
  3. Understanding front end garbage collection
  4. [continuous update] front end special style implementation
  5. Flutter product analysis and package reduction scheme
  6. XPath positioning
  7. 前端开发css中的flex布局的使用
  8. The use of flex layout in front end development CSS
  9. JQuery核心函数和静态方法
  10. JQuery core functions and static methods
  11. Node family - understanding of blocking and non blocking
  12. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  13. Vue source code analysis (2) initproxy initialization proxy
  14. What's TM called react diff
  15. Summary of common front end data structure
  16. Useeffect in hooks
  17. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  18. Front end notes: virtual Dom and diff of vue2. X
  19. The best code scanning plug-in of flutter
  20. The simplest plug-in for rights management of flutter
  21. 21. Object oriented foundation "problems and solutions of object traversal"
  22. Discussion on hot micro front end: Google AdWords is a real micro front end
  23. Usecallback and usememo for real performance optimization
  24. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  25. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  26. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  27. Transaction of spring's reactive / imperative relational database
  28. The implementation of hexagonal hexagonal reactjs Janos pasztor
  29. HTTP状态码:402 Payment Required需要付款 - mozilla
  30. HTTP status code: 402 payment required - Mozilla
  31. Factory mode, constructor mode and prototype mode
  32. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  33. Cocos Quick Start Guide
  34. Comparison of three default configurations of webpack5 modes
  35. A case study of the combination of flutter WebView and Vue
  36. CSS: BFC and IFC
  37. A common error report and solution in Vue combat
  38. JS: this point
  39. JS: prototype chain
  40. JavaScript series -- promise, generator, async and await
  41. JS: event flow
  42. Front end performance optimization: rearrangement and redrawing
  43. JS - deep and shallow copy
  44. JavaScript异步编程3——Promise的链式使用
  45. JavaScript asynchronous programming 3 -- chain use of promise
  46. Vue.js组件的使用
  47. The use of vue.js component
  48. How to judge whether a linked list has links
  49. Element UI custom theme configuration
  50. Text image parallax effect HTML + CSS + JS
  51. Spring的nohttp宣言:消灭http://
  52. Vue3 intermediate guide - composition API
  53. Analysis of URL
  54. These 10 widgets that every developer must know
  55. Spring's nohttp Manifesto: eliminate http://
  56. Learn more about JS prototypes
  57. Refer to await to JS to write an await error handling
  58. A short article will directly let you understand what the event loop mechanism is
  59. Vue3 uses mitt for component communication
  60. Characteristics and thinking of ES6 symbol