person typing
Create A Todo API Using Express

In this tutorial, I will show how to make an API with the express which is actually a javascript framework.

So let's get started

First of all, make sure you have set up Node Js in your local pc, this tutorial I'm going to use VS code editor , make sure it also has in your local pc.

First, make a project folder like todos_api then open it with your vs code editor

Then do

js
git init -y

For initial your project, it will make a package.json file in your project directory, after that install two package in your root project directory.

js
npm install express
npm install shortid

After that you should see in your package.json file like:

js
{
"name": "basic_express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"shortid": "^2.2.16"
}
}

nodemon index.js for this line make sure you have install nodemon, it should be global or in your local project directory and make a file called index.js in your project root directory

js
# Install nodemon
npm install nodemon
# Install nodemon globally on your machine
npm install -g nodemon
# Install nodemon on your project as dev-dependency
npm install nodemon --save-dev

File Directory

file
> |> node_modules
> |.gitignore
> |controller.js
> |index.js
> |package-lock.json
> |package.json
> |routes.js

Then make a simple server with express js

js
const express = require('express')
const app = express()
app.use(express.json())
app.get('/', (req, res) => {
res.send('I am alive')
})
app.listen(4000, () => {
console.log('Server is running on port 4000')
})

Now if you run localhost:4000 then you should see the output in the browser I am alive

This project is about to Create, Read, Update and delete (CRUD) application

note
/**
* HTTP Verbs or Methods
* - GET (get a list of data or single object of data)
* - POST (create new resources)
* - PUT (Update -> whole object)
* - PATCH (Update -> update specific propertices)
* - DELETE (Delete the resource)
*
* Resource URI
* - GET (/todos)
* - POST (/todos)
* - GET (/todos/todosId)
* - PUT/PATCH (/todos/todosId)
* - DELETE (/todos/todosId)
*/

For more please read from here

Create a Todo list

First of all, we will create a todo list with post request controller

routes.js

js
const router = require('express').Router()
const controller = require('./controllers')
router.post('/', controller.create)
module.exports = router

Here, actually I have make a routes which is connected with a create controller,

controllers.js

js
var shortid = require('shortid')
const todos = []
exports.create = (req, res) => {
const { text } = req.body
const todo = {
id: shortid(),
text,
isCompleted: false,
created: new Date(),
}
todos.push(todo)
res.status(201).json({ message: 'todos created succesful', ...todo })
}

Now we have routes and controllers but still our project will not run, because still we didn't connect our project with our main root file which will render from index.js file, so let's update our index file.

index.js

js
const express = require('express')
const app = express()
app.use(express.json())
app.use('/todos', require('./routes'))
app.get('/', (req, res) => {
res.send('I am alive')
})
app.listen(4000, () => {
console.log('Server is running on port 4000')
})

just add app.use("/todos", require("./routes")); this line.

In this article we will use thunderclient for check our API, it's a VS code extension you can add from here or you can manually add from your VS code extension tab.

Upto this point if everything is ok, then open your thunderclient and tab on new button then you need to input your current localhost address which you had use in your project localhost:4000, remember your initial routes starts with /todos, so your address will be localhost:4000/todos then in the body section required a text, after doing this tab on the send button, then you mayb see

random stuff

Now I'm going to add all routes which will be include in our project which is GET, POST, PUT and PATCH

routes.js

js
const router = require('express').Router()
const controller = require('./controllers')
router.delete('/:todoId', controller.deleteTodos)
router.patch('/:todoId', controller.patchUpdateById)
router.put('/:todoId', controller.putUpdateById)
router.get('/:todoId', controller.findById)
router.get('/', controller.findAll)
router.post('/', controller.create)
module.exports = router

Find All todos

It should be a get request which will show all data, that we already had import data with the post request.

controllers.js

js
var shortid = require('shortid')
const todos = []
exports.findAll = (req, res) => {
const result = todos.map(todo => ({ id: todo.id, text: todo.text }))
return res.status(200).json(result)
}

I just added content three more times with the post request, now if you want to see all data then just select get request with the same routes which is localhost:4000/todos (GET request)

random stuff

Find todos by id

controllers.js

js
var shortid = require('shortid')
const todos = []
exports.findById = (req, res) => {
const { todoId } = req.params
const todo = todos.find(todo => todo.id === todoId)
return res.status(201).json(todo)
}

When we have created a todos with the post request then we have seen, that we have imported data like text, shortid, isCompleted (which is default false), Date, we can't seen those data in the get request when we had to find all data, because I have find just text and id, but in the findById routes we have find all information from our ontime database.

Then our output should be

random stuff

Update todo by PUT request

controllser.js

js
var shortid = require('shortid')
const todos = []
exports.putUpdateById = (req, res) => {
// if the item is not exist the then create one
// if it exist then update
const { text, isCompleted } = req.body
const { todoId } = req.params
const todo = todos.find(todo => todo.id === todoId)
if (!todo) {
// will be new create
const todo = {
id: shortid(),
text,
isCompleted: false,
created: new Date(),
}
todos.push(todo)
res.status(201).json({ message: 'updated new todos created', ...todo })
} else {
// update
;(todo.text = text || todo.text),
(todo.isCompleted = isCompleted || todo.isCompleted)
const index = todos.findIndex(todo => todo.id === todoId)
todos[index] = todo
res.status(201).json({ message: 'todos updated', ...todo })
}
}

In the put or update request first we have to verify the id if id match with the current content then just go with else condition and update our old todos then save it with todos array, but if we do not find any todos with that id then just make a new todos with unknown id, you should run and check this one.

update todos with patch request

controllers.js

js
var shortid = require('shortid')
const todos = []
exports.patchUpdateById = (req, res) => {
const { todoId } = req.params
const { text, isCompleted } = req.body
const index = todos.findIndex(todo => todo.id === todoId)
if (index === -1) {
return res.status(404).json({ message: 'Todo not found' })
}
todos[index].text = text || todos[index].text
todos[index].isCompleted = isCompleted || todos[index].isCompleted
res.status(201).json({ message: 'Todo updated succesfully', ...todos[index] })
}

In this patch request first of all check the id and remember it will check with the value of the index, if find the id then just update the index number or show the message Todo not found, please check and run it, if you faced any problem then write in the comment box about your problem.

Delete todos

controllers.js

js
var shortid = require('shortid')
const todos = []
exports.deleteTodos = (req, res) => {
const { todoId } = req.params
const index = todos.findIndex(todo => todo.id === todoId)
todos.slice(index, 1)
}

Delete routes will delete the whole resources with find the todos id then just slice index number.

all posts

©2021-2021 DevsrcBlog. All rights reserved.