Member-only story
Creating REST API routes in Node.js — Part 2
Hi folks, in the part 1 blog I shared the steps for setting and running up the node.js port. Today I want to continue this journey by creating routes. I choose the Todos app for which I’ll write Create, Read, Update, and Delete (CRUD) todos APIs.
Create todosController
Create a backend
folder in your project and add a controllers
folder in it.
All the features logic will go here with separate controller files. So now I'll add a todosController.js
file and create simple CRUD functions.
const getTodos = (req, res) => {
res.status(200).json({message: 'Get todos'})
}
const setTodo = (req, res) => {
res.status(200).json({message: 'Set todo'})
}
const updateTodo = (req, res) => {
res.status(200).json({message: `Update todo ${req.params.id}`})
}
const deleteTodo = (req, res) => {
res.status(200).json({message: `Delete todo ${req.params.id}`})
}
module.exports = {
getTodos,
setTodo,
updateTodo,
deleteTodo
}
I’ll get the id
in the query param for update and delete todo API. I am just returning a static JSON message right now. I'll later replace it with the actual code.
Create a routes file
So now I’ll add a todoRoutes.js
file inside /backend/routes
folder and initialize the router…