In this blog post, we will be building a simple Todo API using Express.js. This API will allow us to create, read, update, and delete todos.
Setting Up the Server
First, we need to set up our server. We will be using Express.js, a fast, unopinionated, and minimalist web framework for Node.js.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
Creating the Todo List
Next, we will create an array to store our todos.
const todos = [];
Creating the Routes
Now, letβs create the routes for our API.
GET /todos
This route will return all the todos.
app.get('/todos', (req, res) => {
res.send(todos);
});
POST /todos
This route will create a new todo.
app.post('/todos', (req, res) => {
const { title, description } = req.body;
if (!title || !description) {
return res.status(400).send("title and description are required");
}
const newTodo = {
id: Math.floor(Math.random() * Date.now()),
title,
description
};
todos.push(newTodo);
res.send(newTodo);
});
PUT /todos/:id
This route will update a todo.
app.put('/todos/:id', (req, res) => {
const { title, description } = req.body;
if (!title || !description) {
return res.status(400).send("Title and Description are required");
}
const todoIndex = todos.findIndex(todo => todo.id === parseInt(req.params.id));
if (todoIndex === -1) {
return res.status(404).send("Invalid Index");
}
const updatedTodo = { title, description };
Object.assign(todos[todoIndex], updatedTodo);
res.send("Todos are updated");
});
DELETE /todos/:id
This route will delete a todo.
app.delete('/todos/:id', (req, res) => {
const todoIndex = todos.findIndex(todo => todo.id === parseInt(req.params.id));
if (todoIndex === -1) {
return res.status(404).send("Invalid Index");
}
todos.splice(todoIndex, 1);
res.send('Deleted Todo');
});
Error Handling
Lastly, we will add some error handling to our server.
app.use((err, req, res, next) => {
console.log(err.stack);
if (err instanceof SyntaxError) {
res.status(400).send("Bad Request");
} else {
res.status(500).send("something broke!");
}
})
Starting the Server
Finally, we will start our server.
app.listen(3000, () => {
console.log("App listening at port 3000")
});
And thatβs it! We have built a simple Todo API using Express.js. Happy coding!π
Top comments (0)