How to structure an Express.js REST API: best practices (2023)

So he decided to join thousands of other companies and use Express.js to build a REST API. How should you structure your project?

One of the best things about Express is that it's a very lightweight and unbiased framework, making it extremely flexible to configure.

A possible downside is that there aren't many guides on how to structure applications. This can lead to maintenance and scaling issues.

In this post, we discuss some best practice approaches to creating a robust and high-performance Express REST API project.

Why is structure important?

Why is structure important? Why not take a "move fast and break things" approach and put your code where it seems to work?

Without good structure, your code becomes increasingly difficult to understand and easier to accidentally break things. This means that errors increase and implementations become slower and riskier.

If you plan on scaling your API, the choices made above should support you. Otherwise, you will have to spend a lot of time and money to rewrite your application.

important concepts

While there are a variety of recommendations below, they are all based on the same principles:

  • separation of interests. Organize functions and modules to ensure they have a clear, single task, ensuring your code is easy to read and maintain.
  • Modular architecture. Build your app in isolated, easy-to-understand chunks. This ensures that your code is flexible and recompilable for cron jobs, unit tests, etc.

With these principles in mind, you'll know what to do when your needs exceed those presented here and in other examples.

Separate application and server

The first thing you'll typically do in an Express API project is set up a simple application and assign it to an HTTP server. This is commonly, but incorrectly, done in a single file:

const app = express()app.use(bodyParser.json())app.use('/api/products', produtos)app.use('/api/orders', orders)const port = process.env.PORT || '3000'aplicación.escucha(porto)

Since there are two entities here, the application and the server, they need to be separated. Not just in principle, but also because the separation of the application and the server also allows you to unit test your application without initializing the server.

So let's transform that. we will have aapplicationFolder where we save the application code and create aindex.jsModule in the same where we configure the app.

(Video) Folder Structure for API's - Beginner, Intermediate, and Advanced

const express = require('express')const app = express()app.use(bodyParser.json())app.use('/api/products', products)app.use('/api/orders', orders )module.exports = aplicativo

we put theserver.jsFile in the root directory of the project. This file imports the application and assigns an HTTP server. It also serves as the entry point for our application.

const app = require('./app') const port = process.env.PORT || '3000' application.listen(porta)

We could also add additional network-related settings to this file, vhosts, SSL, etc.

Three-tier application architecture

To structure our API application, we use the popular "three-tier architecture".

First layer of fabric.Responsible for sending, receiving and validating HTTP requests. General configuration here includes routes, controllers and middleware.

2. Service layer.Contains business logic.

3. Data Access Layer.Where we read and write to a database. We usually use an ORM like Mongoose or Sequelize.

This architecture creates a good separation of concerns that makes the code easier to read and maintain.

It's also modular enough to allow recomposition. For example, you might want to create frontends for cron jobs or CLI commands. These can perfectly replace the web layer.

Now let's take a closer look at these layers and their contents.

head web

In the web layer, we process HTTP requests, send data to the service layer and return an HTTP response.

everything with himrequiredyresolutionObjects live here. The main abstractions we use in this layer are:

  • routesWhere you declare the API endpoints route and assign controllers.

    (Video) Node JS Express Project Structure : Best Practices

  • Middleware.Reusable plugins for modifying requests, typically used for cache control, authentication, error handling, etc.

  • Controller.Methods that process an endpoint and unpack data from the web layer to send to services.

Here is an example file structure withproductsyUsernameexample entities.

app index.js path products.js users.js Controller products.js users.js Middleware cacheNoStore.jsserver.js

routes

In simple projects, you often see routes and logic declared together:

app.use('/api/productos/:id', (req, res) => {// Logik hier})

A better practice is to abstract the routes into a module responsible for assigning the routes to controller methods.

It's also a good idea to have a separate routes file for each API entity, for example products, users, etc.

Here is an example route file:

const controladores = require('./controller.js')const router = require('express').Router()module.exports = () => { router.get('/', controllers.allProducts) router.get ('/:id', controladores.getProduct) router.post('/', controladores.createProduct)}

If you have reusable features like cache checking, access checks, or input validation, it's a good idea to abstract them into middleware plug-ins.

These can be applied per route in the route file:

const cacheNoStore = require('./middleware/cacheNoStore.js')module.exports = () => { router.get('/:id', cacheNoStore, controllers.getProduct)}

After creating your route modules, you can declare them in your application's index file. Note that a route prefix can also be defined here.

app.use('/api/products', require('./routes/products')) app.use('/api/orders', require('./routes/orders'))

💡

(Video) RESTful APIs in 100 Seconds // Build an API from Scratch with Node.js Express

A great resource for creating REST APIs is the articleThe 10 commandments of CALM

Controller

Best practice for controllers is to keep them clear of business logic. Your only task is to get all the relevant data from therequiredobject and send it to services. The return value must be ready to be included in a responseresolution.

Make sure you don't use web layer objects (i.e.required,resolution, headers, etc.) in your services. Instead, unpack all values ​​like URL parameters, header values, body data, etc. before sending them to the service layer.

Here is an example of a controller module.

const { getProduct } = require('../services/products')module.exports = () => {getProduct: async (req, res) => {try {const id = req.params.idconst product = await getProduct (id)res.json(producto)}captura (err) {res.status(500).send(err)}}}

data access layer

The last layer to consider in our application framework is the data access layer. This is the layer that communicates with your database.

Most modern applications use an ORM likeMungoofollowThe templates you create for this will serve as your data access layer.

appindex.jsroutesproducts.jsusers.jscontrollersproducts.jsusers.jsmiddlewarecacheNoStore.jsmodelsproduct.jsuser.jsservicesproducts.jsusers.jsserver.js

separation into components

In some scenarios, you might want to consider another level of separation: components.

as explained noNode - site best practicesIf you have logically separate API functions (for example, an admin API and a user API), it's a good sign that they should be separated into components.

To implement a component framework, theapplicationThe folder we considered above would be refactored and duplicated to be named per entity.

Note that we provide common folders for middleware and templates as they are likely to be shared utilities.

productsindex.jsroutes.jscontrollers.jsservices.jsusersindex.jsroutes.jscontrollers.jsservices.jsmiddlewarecacheNoStore.jsmodelsproduct.jsuser.jsserver.js

Component Benefits

💡

If you want to build and scale a higher level API with Express, consider doing that too.Triple.

(Video) How to implement Clean Architecture in Node.js (and why it's important)

Treblle is API monitoring software that can be installed in a quick application with just a few lines of code. Monitor and track any issues with your API so they can be identified and fixed before they affect your usage.

In fact, Trebelle JS SDK also supports Node, Express, KoaJS, Strapi and Cloudflare Workers.

In addition to API monitoring, Treblle offers a variety of other useful features for your business, including:

  • Automatically generated API documentation

  • API Quality Ratings

  • 1 click test

And more. Trebelle is free for up to 30,000 requests and takes a few minutes to install, so give it a try.Try!

To involve

Express is one of the most popular Node.js frameworks, prized for its speed and flexibility. However, if you're not careful, it's easy to create a wild codebase that becomes tedious to maintain and scale.

By practicing the principles of separation of concerns and modular architecture, we can ensure that our Express APIs are both robust and flexible.

FAQs

Is Express GOOD FOR REST API? ›

Express is a perfect choice for a server when it comes to creating and exposing APIs (e.g. REST API) to communicate as a client with your server application. Previously you have already implemented one Express route, which sends a "Hello World!", that you have accessed via the browser and cURL.

What are the best practices to design a REST API? ›

Collections, Resources, and their URLs
  • Understanding resources and collections. Resources are fundamental to the concept of REST. ...
  • Nouns describe URLs better. ...
  • Describe resource functionality with HTTP methods. ...
  • Give feedback to help developers succeed. ...
  • Give examples for all your GET responses. ...
  • Handle complexity elegantly.

How would you structure a REST API? ›

Any REST request includes four essential parts: an HTTP method, an endpoint, headers, and a body. An HTTP method describes what is to be done with a resource.
...
REST API methods and request structure
  1. POST to Create a resource,
  2. GET to Retrieve a resource,
  3. PUT to Update a resource, and.
  4. DELETE to Delete a resource.
Nov 19, 2022

What are the 4 steps of the REST API in the URL? ›

Step #1 – Enter the URL of the API in the textbox of the tool. Step #2 – Select the HTTP method used for this API (GET, POST, PATCH, etc). Step #3 – Enter any headers if they are required in the Headers textbox. Step #4 – Pass the request body of the API in a key-value pair.

Why not to use Express? ›

However, Express is too heavy and slow

The previous measurements do not only show that express is slow, it means that you need double CPU utilization to perform simple operations, …

Should I use gRPC or REST API? ›

gRPC is roughly 7 times faster than REST when receiving data & roughly 10 times faster than REST when sending data for this specific payload. This is mainly due to the tight packing of the Protocol Buffers and the use of HTTP/2 by gRPC.”

Is ExpressJS obsolete? ›

Express is not being deprecated. The current version is Express 4. Express 5 is on the way to being introduced. Some features of Express 4 will be deprecated in 5.

What are the 3 principles for a RESTful API? ›

The only requirement is that they align to the following six REST design principles - also known as architectural constraints:
  • Uniform interface. ...
  • Client-server decoupling. ...
  • Statelessness. ...
  • Cacheability. ...
  • Layered system architecture. ...
  • Code on demand (optional).

What are the 3 components of a RESTful API? ›

REST Components
  • Resource Path (request target)
  • HTTP Verb.
  • Body.
  • Header.
Jan 10, 2023

What are your top 5 priorities when creating an API? ›

If anyone should understand how to make a web API that's easy-to-use, it's you.
...
So with that said, let's proceed and talk about the 5 Golden Rules for Designing a Great Web API, namely:
  • Documentation.
  • Stability and Consistency.
  • Flexibility.
  • Security.
  • Ease of Adoption.

What are the 4 most common REST API operations? ›

For REST APIs built on HTTP, the uniform interface includes using standard HTTP verbs to perform operations on resources. The most common operations are GET, POST, PUT, PATCH, and DELETE.

Which framework is used for REST API? ›

Because the REST API is within the integration framework, the REST API can use process automation engine authentication, authorization, and system properties. The REST API controller is a servlet.

What are the key components of REST architecture? ›

Such elements are referred to as the REST architectural elements.
...
REST Architectural Constraints
  • Client-Server.
  • Stateless.
  • Cache.
  • Uniform Interface.
  • Layered System.
  • Code-On-Demand.

What are the 6 constraints of REST API? ›

Architectural Constraints of RESTful API: There are six architectural constraints which makes any web service are listed below:
  • Uniform Interface.
  • Stateless.
  • Cacheable.
  • Client-Server.
  • Layered System.
  • Code on Demand.
Jan 5, 2023

What is API architecture diagram? ›

An API diagram is a form of software diagram. It is a graphical overview of the architecture and operational logic of an API, which helps designers and architects to make key decisions early in the development lifecycle of an API.

What is the difference between REST API and RESTful API? ›

Put simply, there are no differences between REST and RESTful as far as APIs are concerned. REST is the set of constraints. RESTful refers to an API adhering to those constraints. It can be used in web services, applications, and software.

What are the 3 types of APIs? ›

Today, there are three categories of API protocols or architectures: REST, RPC and SOAP.

What is REST API workflow? ›

The Workflow REST API allows you to create, modify, and execute Workflows and Workflow actions via standard REST API calls.

What will replace Express JS? ›

  • 4.1 Koa.
  • 4.2 Fastify.
  • 4.3 Nest.
  • 4.4 Ember JS.
  • 4.5 BackboneJS.
  • 4.6 Vue JS.
  • 4.7 Knockout JS.
  • 4.8 Angular.

How do I secure my Express backend? ›

Take 7 steps to make sure that your app is invincible
  1. Use reliable versions of Express. js.
  2. Secure the connection and data.
  3. Protect your cookies.
  4. Secure your dependencies.
  5. Validate the input of your users.
  6. Protect your system against brute force.
  7. Control user access.
Oct 10, 2019

Do companies use ExpressJS? ›

Who uses ExpressJS? 1909 companies reportedly use ExpressJS in their tech stacks, including Twitter, Accenture, and Stack.

Why gRPC is not widely used? ›

As CircleCI reports, gRPC can also be fragile and more complex than the alternatives. Thus, it's not always the best solution for every problem in which the need for high-speed communication over a network is a critical factor.

What are the disadvantages of gRPC over REST? ›

Weaknesses of gRPC

As gRPC heavily uses HTTP/2, it is impossible to call a gRPC service from a web browser directly. No modern browser provides the control needed over web requests to support a gRPC client. Therefore, a proxy layer and gRPC-web are required to perform conversions between HTTP/1.1 and HTTP/2.

Is gRPC deprecated? ›

gRPC C-core is in maintenance mode and will be deprecated in favor of gRPC for . NET. gRPC C-core is not recommended for new apps.

Will next js replace Express? ›

Next. js doesn't replace Express and you can use them together. Next. js uses some Node.

How scalable is ExpressJS? ›

Express. js has proven to be very scalable over the years because of the number of large companies using the framework on their server daily. It handles user requests and responses efficiently and requires little to no extra configuration when developing a large-scale web application.

Is Express faster than spring boot? ›

Express is better because it uses node. js which can handle high traffic simultaneously. Whereas Spring uses java which is ofcourse much faster than node. js, but its not good for simultaneous larger traffic handling.

What are the four principles of REST architecture? ›

REST principles are defined by four interface controls, including identifying resources, managing resources through representations, self-descriptive communications, and hypermedia as the engine of the application state.

What are two main guiding principles of REST? ›

Principles of Rest API

In a REST API design, client and server programs must be independent. The client software should only know the URI of the requested resource; it should have no additional interaction with the server application.

What is the difference between REST API sync and async? ›

Asynchronous Writes. Synchronous API calls are blocking calls that do not return until either the change has been completed or there has been an error. For asynchronous calls, the response to the API call is returned immediately with a polling URL while the request continues to be processed.

Is RESTful API frontend or backend? ›

REST and GraphQL are both standard ways to develop backend APIs. But over the past decade REST APIs have dominated as a choice for developing backend API's. And many companies and developers use it actively in their projects. But REST has some limitations, and there's another alternative available – GraphQL.

What defines a good REST API? ›

Good REST APIs:
  1. are well-documented and reliable.
  2. use HTTP verbs as Fielding originally defined.
  3. support X-HTTP-METHOD-Override to accommodate picky proxies.
  4. express URLs with nouns rather than verbs.
  5. track version.
  6. make expressive use of HTTP Status Codes.
  7. handle errors carefully and explicitly.
  8. log activity.

What are the two formats of the RESTful API? ›

The REST API supports the following data formats: application/json. application/json indicates JavaScript Object Notation (JSON) and is used for most of the resources. application/xml indicates eXtensible Markup Language (XML) and is used for selected resources.

What does an effective API strategy look like? ›

What Does an Effective API Strategy Look Like? An effective API strategy includes full lifecycle API management, strong security, an impressive API portal, and insightful analytics. With an effective API strategy, you can drive innovation in the enterprise and gain a competitive advantage.

What are KPIs for APIs? ›

With the key role Application Programming Interfaces (APIs) play in daily business operations, API Key Performance Indicators (KPIs) are now deeply interwoven with today's business strategies. The more closely you measure your API KPIs, the more likely you are to effectively manage them for performance improvements.

What makes an API successful? ›

A good API must be able to limit the amount of data that can be received in one go, as well as the frequency of requests for data. It should also be able to notify about how many “pages” of the data are left.

What is an Express API? ›

API Using Express and Its Architecture. Conclusion. Restful API is very popular and commonly used to create APIs for web-based applications. Express is a back-end web application framework of node js, and with the help of express, we can create an API very easily.

What is the format of an API call? ›

The bulk API supports both JSON and CSV file formats as data sources for PUT and POST requests. The bulk API does not support XML. For PUT and POST requests, you must specify either application/json or text/csv in the Content-Type header: if you do not include the Content-Type header an error will occur.

Is Express a full stack framework? ›

Two common full-stack JavaScript stacks are: MEAN stack - MongoDB (database), Express (server), Angular (front-end framework), and Node (runtime environment)

How to build REST API with Express? ›

js REST API with the Express Framework, expose it to the internet with Ngrok and make test requests to it on Postman.
  1. Introduction. ...
  2. Prerequisites. ...
  3. Step 1 — Build and Run an Express Server with Node. ...
  4. Step 2 — Create a GET Endpoint. ...
  5. Step 3 — Expose Server with Ngrok. ...
  6. Step 4 — Test Requests with Postman. ...
  7. Citations & Resources.
Aug 31, 2020

What is REST API in Express JS? ›

Previous Page. An API is always needed to create mobile applications, single page applications, use AJAX calls and provide data to clients. An popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State).

How to make an API with Express JS? ›

  1. Step 1: Create the Required Directories. The first step involved in building a Node js REST API requires you to create directories that will contain the code for the Node js REST API. ...
  2. Step 2: Create Your First App Express API. ...
  3. Step 3: Creating the User Module. ...
  4. Step 4: Creating the Auth Module.
Nov 3, 2021

What are the 5 principles for a RESTful API? ›

Principles of Rest API
  • Client-Server decoupling. In a REST API design, client and server programs must be independent. ...
  • Uniform Interface. All API queries for the same resource should look the same regardless of where they come from. ...
  • Statelessness. ...
  • Layered System architecture. ...
  • Cacheable. ...
  • Code on Demand.
Jan 18, 2023

What are the three layers of API? ›

API Led Connectivity talks about three layers like Experience API, Process API and System API. Each layer has its own roles, responsibility and functionality. API Led Connectivity is an architectural style that connects data to application through reusable and purposeful API.

What is a good API documentation layout? ›

Your API documentation should be in the simplest form possible, yet it shouldn't leave out any important details. Also, make sure you explain acronyms and tech terms the first time you use them, or put them in a glossary toward the end of the documentation.

What is the difference between API and REST API? ›

An API, or application programming interface, is a set of rules that define how applications or devices can connect to and communicate with each other. A REST API is an API that conforms to the design principles of the REST, or representational state transfer architectural style.

What are 2 popular formats for request and response? ›

The most common formats found in modern APIs are JSON (JavaScript Object Notation) and XML (Extensible Markup Language).

Is ExpressJS outdated? ›

Express is not being deprecated. The current version is Express 4.

What is better than ExpressJS? ›

Fastify is another popular open-source web framework for the Node environment that is primarily famous for its speed, i.e., it is up to 20% faster than Express in almost every request. It provides full encapsulation for plug-ins, parses incoming requests into JSON with faster rendering, and provides quick routing.

Videos

1. Node.js Express Project to Build Fake REST CRUD API From JSON Using JSON Server Library in Browser
(Coding Shiksha)
2. Designing a clean REST API with Node.js (Express + Mongo)
(Dev Mastery)
3. How to build a REST API with Node js & Express
(Programming with Mosh)
4. Writing a professional API in express JS with best practices
(Grown Academy)
5. 9 Best practices for designing REST APIs like a Pro (in 1 hr) | Node.js & Express | Beginners' guide
(AB Satyaprakash)
6. How To Structure Your Node js Project To Fit Industry Standard Using RCSM Layered Architecture
(makeThemTech)

References

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated: 11/21/2023

Views: 6725

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.