his tutorial will focus on one of my favorite techniques for structuring the route files. This approach uses the folder and file structure to build the API.

What are we building?

Following in the footsteps of all great tutorials, we will build a **todo **list API. This will provide the following endpoints.

  • GET /todo-item (Returns all todo items)
  • CREATE /todo-item (Adds a new todo item)
  • GET /todo-item[id] (returns the todo item with the id)
  • UPDATE /todo-item/[id] (updates a todo item with the id)
  • DELETE /todo-item/[id] (deletes the item with the id)

A todo item will have the below structure.

  • id (string — unique id)
  • title (string — title of the todo item)
  • status (boolean —if the todo item is completed)

Note: To keep the tutorial simple, we will store the items in memory.

Basic setup

Before we proceed, lets set up an API we can play around with.

Run the following commands to make a directory and cd into it.

mkdir dynamic-routes
cd dynamic-routes

Next, run the following to initiate an npm project (the “-y” flag tells it to use default values)

npm init -y 

Run the following command to install all the required packages

npm i express body-parser express-promise-router 
  • express: Fast, unopinionated, minimalist web framework for node.
  • body-parser: Middleware for parsing incoming request bodies
  • express-promise-router: wrapper for Express 4’s Router that allows middleware to return promises

Install nodemon using the below command. This will restart the server whenever a file is changed. (The “-D” flag installs it as a dev dependency)

npm i -D nodemon

Next, make an “src” folder for all of our code and add an index.js file inside.

mkdir src && touch src/index.js

Next, update the package.json file with the following. This main will tell npm where to find our entry file. and secondly, the scripts will provide us with a way to run nodemon.

{

... 
"main": "src/index.js", // update this line
"scripts": {
"start": "nodemon" // add this to the scripts
},
...
}

#expressjs #fastify #dynamic-programming #api-development #routing

A Simplified Technique for Express Routing
1.35 GEEK