How to Structure Your Nodejs REST API
nodejs
82
REST API
6
backend
7
White

Duy Tùng viết ngày 24/04/2019

Introduction

Developing a well-structured backend API is extremely important for a website. Hence, as an aid for those who are struggling with your backend structure, I will present a backend architecture that I often use down below. This structure is based on the course I learnt from PluralSight - API Design in Node.js Featuring Express & Mongo. I hope some of you might find this blog helpful :smile:

Prerequisite

I will assume that you already have some experiences with Nodejs before. If you don't, I highly recommend taking a course on YouTube or Pluralsight. I did mention how to learn Nodejs in my previous blog - For newbies - How to get started (Based on my experience).

External Structure

The picture below is the external structure for your API
alt text
As you can see, there is an index.js file. This file will grab the config, app, and logger exported from the server folder and then run the application.
alt text

Internal Structure

We will explore the server folder
alt text
In the server.js file, you will:

  • Create the express app
  • Connect to the database
  • Clean & Seed the database(import from other files)
  • Set up the app middleware (import from other files)
  • Set up the routes (import from other files)
  • Capture and handle the errors
  • Export the express app (index.js needs this) alt text

Api

alt text
Each class (model) will be in a different model and the api.js will put these folders together using router.
alt text
Router is a very good module in structuring your API. Router is like app in express but with smaller scope. The difference is that you can have multiple routers, each handling a sub path but you can only have one app.
For instance, the router of app.js map the two routers exported from ./user/userRoutes and ./session/sessionRoutes with their respective paths (/users. and /sessions)

In each class folder, there are 3 files:

  • Model: define the structure of you model
  • Controller: define the functions you can use to manipulate the data in this model
  • Routes: match the functions defined in controller to the path (using router)

You can have a look at two of my model folders for example (I will attach the link in the conclusion part)

Auth

alt text
Most of the websites nowadays need athentication/authorization. In my API, I use token authentication and I put it in the Auth folder. You can extend it with Facebook, Google authentication if you want

There are three files in this folder:

  • auth.js: Define the functions within the signin process (e.g. verify the user, get the user)
  • controller.js: Use the auth.js functions to send the response to the client when they signin
  • routes.js: Map the controller function with the path and add middlewares

REMEMBER: You also need to add extra methods to User model in order to encrypt and compare password.

Config

alt text
The config folder defines the environment variables for the API. Depending on which phase you are in (development, production, testing), import the appropriate environment to the config.js file.

Middleware

alt text
This middleware file lists all the middlewares your app might need. Some of them are essential for every app (bodyParser, cors, override, morgan). You can add more middlewares if necessary.

Public

This folder is used to store your pictures, files, etc.
You can host these files using middleware in your middleware folder

Util

This folder consists of things that you will use in many places in you program
For example, I use a separate logger (it looks better :stuck_out_tongue_closed_eyes:), a seed.js file for cleaning and seeding the database after each time the server restart, and a upload file for uploading pictures.

Conclusion

Although I think this is a really good API structure, you can change it to adapt to your specific project needs if you want.
For the whole backend API, please check it out in my GitHub account. I also developed a REST API in Python - Flask if you like Python :sweat_smile:
If you have any questions or other ideas about this, please give some comments down below, I really appreciate it. Have fun coding and I will see you in my next blog.

DuyTungHa :books: University of Wollongong, Australia :facepunch: 22-04-2019

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

White

Duy Tùng

3 bài viết.
3 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
White
5 3
This is my first blog post on Kipalog. I'm a freshman in Wollonong University, Australia and currently studying Bachelor of Computer Science. I've ...
Duy Tùng viết 7 tháng trước
5 3
White
4 8
Introduction Hi guys, as you already know, problem solving is one of the indispensable skills that developers and software engineers need to posses...
Duy Tùng viết 2 tháng trước
4 8
Bài viết liên quan
White
24 4
Lời mở đầu API ngày càng phổ biến và chắc chắn ngày càng cần thiết hơn trong quá trình phát triển của ngành Phần Mềm. Dĩ nhiên như anh Phil Sturgeo...
Tùng Đặng Thanh viết hơn 3 năm trước
24 4
White
1 0
Lâu lâu không động vào nodejs không biết mấy ông tool tiếc này đi đâu về đâu rồi. Trước đây thì mình vẫn có thể dùng istanbul với mocha đơn giản th...
Hà Phạm viết gần 3 năm trước
1 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


White
{{userFollowed ? 'Following' : 'Follow'}}
3 bài viết.
3 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!