Skip to content

So, you want to create REST API using Node.js? This is the reference you need to build the right recipe.

License

Notifications You must be signed in to change notification settings

yogski/awesome-nodejs-rest-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Awesome Node.js REST API Reference

So, you want to create REST API service using Node.js? This is the reference you need to build the right recipe.

This guide is created to address developer's pain points when creating REST API service:

  1. I want to make informed decision on which framework to choose --> Check this out
  2. Does framework X has Y feature ? --> Here's the full map
  3. What is a good package to handle Z stuff? --> Check the alternatives here
  4. How can I make full REST API service that suits my requirements ? --> Check out our curated recipes

Table of Contents

Frameworks

Framework is the backbone of any web app. Choosing the right framework is critically important. In this section, there will be list of famous Node.js frameworks and comparison of their features. By understanding the feature and philosophy of each framework, developer can pick the framework that matches business requirement and team profile.

Below is curated list of well-known and tested Node.js frameworks suitable for bulding REST API. Github repository and documentation links are available for further inquiry. Each framework also has information about its opinion paradigm. It is a simple measure of how a framework forces development in specific way.

On one end, there is opinionated framework where the it defines the right way to create controller, validate inputs, logging, handle errors, etc. On the other end, there is unopinionated one where it defines limited functions to handle basics like requests, response, routing, etc, while developer is expected to solve the rest (which is the reason to make this guide). There is also middle ground I personally called moderate where there is recommended approach for development, but the framework provides extra feature as optional plugin.

No paradigm is better than the others. Opinionated framework reduces time spent for setting configs and finding packages, as well as make development faster and more structured. Unopinionated framework allows developer to choose most suitable packages for specific use case, which is more agile. Also, when performed correctly, it will yield better performance.

Framework Details

Name Description Opinion Paradigm Documentation Github
Express Most well-known Node.js framework (50K+ github stars) that it has its own stack name. Unopinionated docs Github Repo
Koa Developed by Express.js creator. Lightweight and middleware-centric. Perhaps the most unopinionated Node.js framework. Middlewares available for various use cases. Unopinionated docs Github Repo
Fastify Fast and low overhead web framework, for Node.js. It's slim in size with many plugins available. Similar approach to Koa.js, although bit more opinionated. Moderate docs Github Repo
Nest Enterprise-grade open source Node.js framework. 40K likes on Github Opinionated docs Github Repo
Hapi Mature and stable Node.js framework. It is moderately opinionated with various plugins available. Unlike its peers, Hapi hates middleware and excludes it from its core design. Moderate docs Github Repo
Sails A complete MVC Node.js framework. On par with Laravel, Ruby on Rails, and Django. 20K+ stars on Github Opinionated sailsjs.com Github Repo
Adonis A fully featured web framework for Node.js. Emphasized on minimized configuration and productive work. Opinionated docs Github Repo
Restify Node.js framework optimized for battle-tested RESTful web services. Like Express.js without view, with additional functions tailored for web service. Unopinionated docs Github Repo
Feathers Lightweight web-framework for creating apps and REST API. Has plugins available in its ecosystem (it even has Express as plugin!). Also check its awesome-feathers. Moderate docs Github Repo

Framework Features Map

The following table shows built-in features included in each framework.

βœ… = fully available (e.g usable after installing framework)

🟑 = partially available (e.g official package available, can be installed when needed)

Express Koa Fastify Nest Hapi Sails Adonis Restify Feathers
Router βœ… 🟑 βœ… βœ… βœ… βœ… βœ… βœ… βœ…
Static server βœ… 🟑 🟑 🟑 🟑 βœ… βœ… βœ… βœ…
Auth 🟑 🟑 βœ… 🟑 βœ… βœ… βœ… 🟑
DB Driver 🟑 🟑 🟑 🟑 🟑
ORM 🟑 βœ… βœ… 🟑
Middleware βœ… βœ… 🟑 βœ… βœ… βœ… βœ… 🟑
Logging 🟑 βœ… βœ… βœ… βœ… βœ… βœ… 🟑
Testing βœ… 🟑 🟑 🟑 🟑
Generator 🟑 βœ… βœ… βœ… 🟑
Migration 🟑 βœ… βœ…
Template Engine βœ… 🟑 βœ… βœ… βœ… βœ…
File Upload 🟑 βœ… βœ… βœ…
Validator βœ… βœ… 🟑 βœ… βœ… 🟑
HTTP CLient βœ…
Rate Limit βœ…

Libraries

.env variable πŸ› 

Configuring proper .env config is crucial because we don't want to reveal credentials in the codebase.

  • dotenv : Zero-dependency module that loads environment variables from .env file into process.env.
  • env-cmd : A simple node program for executing commands using an environment from an env file.
  • cross-env : Run scripts that set and use environment variables across platforms (⚠️maintenance mode⚠️)

CORS 🚧

Setup CORS for better security control.

  • cors : Node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Auth πŸ—

Authentication and authorization are core features of any REST API. It ensures proper security on back-end. Many solutions are available. Just pick one. One important advice, though: Don't make your own auth algorithm.

Router 🚏

Router is must-have feature for REST API service. It basically map request URL to a controller, and bring relevant data along.

  • koa-router : router middleware for Koa framework

Database Driver πŸ›’

REST API service may need to store or access data from database. Use library below to enable Node.js to connect to specific database. Also, note that some frameworks offer built-in driver.

  • cassandra-driver : Node.js client library for Apache Cassandra and DSE using Cassandra's binary protocol and Cassandra Query Language.
  • couchdb : Offical Apache CouchDB library for Node.js.
  • mongodb : The official MongoDB driver for Node.js.
  • mssql : Microsoft SQL Server client for Node.js
  • mysql: This is a node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.
  • neo4j : The official Neo4j (a graph database solution) driver for JavaScript.
  • pg : Most popular PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings.
  • pg-promise : Promise-based PostgreSQL client for Node.js, built on top of node-postgres.
  • redis : A high performance Node.js Redis client.
  • sqlite : A wrapper library written in Typescript with ZERO dependencies that adds ES6 promises and SQL-based migrations API to sqlite3

ORM πŸ—Ί

ORM is an abstraction layer between Node.js and database. It serves as data model definition, data caching, query builder, input sanitizer, and adapter for various databases, among others.

Developers have divided opinions about ORM. Some love it ❀️, some hate itπŸ’’. There are trade-offs:

  • ORM has some learning curve
  • ORM makes writing complex query cumbersome
  • ORM makes code shorter
  • ORM makes data model consistent with database constraints
  • ORM caches data and reduce loan on database One key takeaway: ORM is valuable for common REST API service with simple query access (e.g CRUD).

Interested in using ORM? Check out top-rated ORM packages below.

  • knex : A batteries-included, multi-dialect query builder for Node.js.
  • mongoose : A MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.
  • sequelize : A promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.
  • waterline : Next-generation storage and retrieval engine, and the default ORM used in the Sails framework. Supports MySQL, MongoDB, neDB, and PostgreSQL.

Request validation ⭕️

Under no circumstances a REST API could fully trust user's input. Invalid input may lead to an error that bring the service down, or worse, an injection attack with catastrophic consequences. That's why validation (including sanitation) is important in any REST API workflow. Check awesome validation packages available below.

  • express-validator : A validator middleware for Express framework, inspired by validator.js.
  • joi : The (self-proclaimed) most powerful schema description language and data validator for JavaScript.
  • validator : A library of string validators and sanitizers.

Rate Limit 🚦

Rate limit is feature of allowing limited number of request per period per IP address/token. For example, user can only send 1000 requests per day, and only 1 request per 10 second is allowed. Otherwise, server will send 429 Too Many Requests HTTP response. It is useful feature when a REST API service has daily/monthly quota, or serve as security measure to prevent attacks.

Serve static files ⚑

  • koa-static : Static file serving middleware for Koa framework.
  • serve-static : Static file serving middleware for Express framework or an.

File upload πŸ–Ό

Some REST API services need capability to receive file as input. Note that file upload With packages below, it is possible.

  • busboy : A node.js module for parsing incoming HTML form data.
  • formidable : A Node.js module for parsing form data, especially file uploads.
  • multer : Node.js middleware for handling multipart/form-data, which is primarily used for uploading files.

Multimedia file 🎞

HTTP client πŸ“‘

REST API receives request and send response through HTTP/HTTPS protocol. But what if the server needs to talk to other services while processing request? HTTP client is the answer. Here is the list of well-known packages.

  • axios : Promise based HTTP client for the browser and node.js
  • bent : Functional HTTP client for Node.js and Browsers with async/await. Incredibly small browser version built on fetch with no external dependencies or polyfills.
  • node-fetch : A light-weight module that brings window.fetch to Node.js
  • superagent : Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features.

Middleware πŸƒ

Logging πŸ“ƒ

Many things happen inside a REST API service. In many cases, it is important to know when exactly something happens, written as records. It can be helpful for tracking errors, tracing fraud, or serving as data source for further analysis. That is the job of logging feature, and you can find suitable one for your project here.

  • bunyan : A simple and fast JSON logging library for node.js services:
  • log4js-node : This is a conversion of the log4js framework to work with node.
  • pino : Very low overhead Node.js logger.
  • signale : Hackable and configurable log
  • tracer : A powerful and customizable logging library for node.js.
  • winston : A simple and universal logging library with support for multiple transports.

Testing 🧐

Testing is important part of development to make sure REST API service works as expected and can handle errors gracefully. For REST API, it is recommended to focus on unit testing and integration testing. Component testing, which is important for front-end, is not a concern here.

  • ava : Test runner for Node.js with a concise API, detailed error output, embrace of new language features and process isolation that lets you develop with confidence πŸš€
  • jest : πŸƒ Delightful JavaScript Testing, for all-round app types
  • mocha : β˜•οΈ Simple, flexible, fun JavaScript test framework for Node.js & The Browser β˜•οΈ
  • supertest : HTTP assertions made easy via superagent.

Documentation πŸ“–

REST API is useless when no one knows how to access it. That's where documentation library comes in. It usually requires REST API definitions, then magically convert it to accessible HTML page.

  • @nestjs/swagger : OpenAPI (Swagger) module for Nest framework
  • apidoc : Generate a documentation from API descriptions in your source code. See live demo.
  • redoc : React-based documentation generator compliant with OpenAPI. See live demo.
  • swagger-ui-express : Generate swagger-ui API docs in Express framework, based on a swagger.json file.
  • typedoc : Documentation generator for TypeScript projects as CLI or npm package.

Process Manager βš™οΈ

Process Manager helps with deployment, ensuring REST API services run without much headache to developer. It handles running and organizing scripts, doing auto-restart, some even have load balancer and logging.

  • forever : A simple CLI tool for ensuring that a given script runs continuously (i.e. forever).
  • nodemon : A tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
  • pm2 : Production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.
  • supervisor : A little supervisor script for nodejs. It runs your program and watches for code changes without worrying about memory leaks and making sure you clean up all the inter-module references.

Other Libraries

Template Engine

Template engine is not essential since most REST APIs return JSON data. But in any case it is needed, here is the list:

Email

Websocket

Encryption

Recipes

Licenses

This project uses MIT license.

Contribution

This project is open for content correction, update, expansion, as well as translation to other language. Simply fork this repository, make necessary changes, then submit a pull request.

About

So, you want to create REST API using Node.js? This is the reference you need to build the right recipe.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published