DEV Community

Vaibhav Gupta
Vaibhav Gupta

Posted on

Building a Simple Todo API with Express.js

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());
Enter fullscreen mode Exit fullscreen mode

Creating the Todo List
Next, we will create an array to store our todos.

const todos = [];
Enter fullscreen mode Exit fullscreen mode

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);
});

Enter fullscreen mode Exit fullscreen mode

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);
});

Enter fullscreen mode Exit fullscreen mode

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");
});

Enter fullscreen mode Exit fullscreen mode

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');
});

Enter fullscreen mode Exit fullscreen mode

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!");
    }
})

Enter fullscreen mode Exit fullscreen mode

Starting the Server
Finally, we will start our server.

app.listen(3000, () => {
    console.log("App listening at port 3000")
});

Enter fullscreen mode Exit fullscreen mode

And that’s it! We have built a simple Todo API using Express.js. Happy coding!😊

Top comments (0)