DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Built API Using Express. js-Full Explanation

In this blog post, we will guide you through building a task manager API using the Express framework. We will walk you through the entire process, from setting up the project to implementing CRUD (Create, Read, Update, Delete) operations for managing tasks. By the end of this tutorial, you will have a solid understanding of how to build a real-life project using Express.

Title: Building a Task Manager API Using Express: A Step-by-Step Tutorial

This Code link

Introduction:
Welcome to our step-by-step tutorial on building a Task Manager API using Express. In this tutorial, we will guide you through the process of setting up an Express application, connecting to a MongoDB database, and creating API endpoints for managing tasks. By following this tutorial, you will gain a comprehensive understanding of how to build a Task Manager API from scratch.

Step 1: Setting Up the Environment
To begin, make sure you have Node.js and npm (Node Package Manager) installed on your machine. Create a new project folder and open a terminal within that folder. Use the following command to initialize a new Node.js project:

npm init
Enter fullscreen mode Exit fullscreen mode

This command will create a package.json file that will track your project's dependencies and other configurations.

Step 2: Installing Dependencies
To build our Task Manager API, we need to install the required dependencies: Express, body-parser, cors, and mongoose. Run the following command in your terminal to install these dependencies:

npm install express body-parser cors mongoose
Enter fullscreen mode Exit fullscreen mode

This command will download and install the necessary packages into your project.

Step 3: Creating the Express Application
Create a new file named server.js and open it in your preferred code editor. Begin by requiring the necessary modules at the top of the file:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
Enter fullscreen mode Exit fullscreen mode

These modules will enable us to set up our Express application, parse JSON and URL-encoded data, and connect to the MongoDB database.

Step 4: Initializing the Express App and Middleware
Initialize the Express app by adding the following code:

const app = express();
Enter fullscreen mode Exit fullscreen mode

Next, enable Cross-Origin Resource Sharing (CORS) and set up the middleware to parse incoming requests:

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Enter fullscreen mode Exit fullscreen mode

CORS allows our API to handle requests from different origins. Body-parser middleware is used to parse request bodies in JSON and URL-encoded formats.

Step 5: Connecting to MongoDB
To connect to a MongoDB database, add the following code:

mongoose.connect('mongodb://localhost/task_manager_db', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
    .then(() => {
        console.log('Connected to the database');
    })
    .catch((err) => {
        console.log('Cannot connect to the database', err);
        process.exit();
    });
Enter fullscreen mode Exit fullscreen mode

This code establishes a connection to the MongoDB database named task_manager_db. Make sure you have MongoDB installed and running locally on your machine.

Step 6: Defining the Task Model
Define the Task model using Mongoose by adding the following code:

const Task = mongoose.model('Task', {
    title: String,
    description: String,
});
Enter fullscreen mode Exit fullscreen mode

This code defines a schema for our tasks, specifying two fields: title and description.

Step 7: Creating API Endpoints
In this step, we will define the API endpoints for our Task Manager API. Add the following code to create the endpoints:

// GET all tasks
app.get('/api/tasks', (req, res) => {
    Task.find()
        .then((tasks) => {
            res.json(tasks);
        })
        .catch((err) => {
            res.status(500).json({ error: err.message });
        });
});
Enter fullscreen mode Exit fullscreen mode

This endpoint handles a GET request to fetch all tasks from the database. It uses the Task.find() method to retrieve all tasks from the MongoDB collection and returns them as a JSON response. If there's an error, it responds with a status code of 500 and an error message.

// GET a single task by ID
app.get('/api/tasks/:id', (req, res) => {
    Task.findById(req.params.id)
        .then((task) => {
            if (!task) {
                res.status(404).json({ error: 'Task not found' });
            } else {
                res.json(task);
            }
        })
        .catch((err) => {
            res.status(500).json({ error: err.message });
        });
});
Enter fullscreen mode Exit fullscreen mode

This endpoint handles a GET request to retrieve a single task by its ID. It uses the Task.findById() method to find the task based on the provided id parameter. If the task is found, it is returned as a JSON response. If the task is not found, it responds with a status code of 404 and an error message.

// POST a new task
app.post('/api/addtasks', (req, res) => {
    const { title, description } = req.body;

    // Check if the

 title field is not empty
    if (!title) {
        return res.status(400).json({ error: 'Title field is required' });
    }

    const task = new Task({
        title: title,
        description: description,
    });

    task.save()
        .then(() => {
            res.json({ message: 'Task created successfully' });
        })
        .catch((err) => {
            res.status(500).json({ error: err.message });
        });
});
Enter fullscreen mode Exit fullscreen mode

This endpoint handles a POST request to create a new task. It expects the request body to contain a title and description. It checks if the title field is not empty. If it is empty, it responds with a status code of 400 and an error message. Otherwise, it creates a new Task instance based on the request body, saves it to the database using task.save(), and responds with a success message.

// PUT/update an existing task
app.put('/api/updatetasks/:id', (req, res) => {
    Task.findByIdAndUpdate(req.params.id, req.body, { new: true })
        .then((task) => {
            if (!task) {
                res.status(404).json({ error: 'Task not found' });
            } else {
                res.json(task);
            }
        })
        .catch((err) => {
            res.status(500).json({ error: err.message });
        });
});
Enter fullscreen mode Exit fullscreen mode

This endpoint handles a PUT request to update an existing task. It expects the id parameter in the URL and the updated task data in the request body. It uses Task.findByIdAndUpdate() to find the task by ID and update it with the provided data. The { new: true } option ensures that the updated task is returned in the response. If the task is not found, it responds with a status code of 404 and an error message.

// DELETE a task
app.delete('/api/deltasks/:id', (req, res) => {
    Task.findByIdAndRemove(req.params.id)
        .then((task) => {
            if (!task) {
                res.status(404).json({ error: 'Task not found' });
            } else {
                res.json({ message: 'Task deleted successfully' });
            }
        })
        .catch((err) => {
            res.status(500).json({ error: err.message });
        });
});
Enter fullscreen mode Exit fullscreen mode

This endpoint handles a DELETE request to remove a task from the database. It expects the id parameter in the URL to identify the task to be deleted. It uses Task.findByIdAndRemove() to find the task by ID and remove it. If the task is not found, it responds with a status code of 404 and an error message. If the task is successfully deleted, it responds with a success message.

// Start the server
app.listen(5000, () => {
    console.log('Server is running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

Finally, the server is started on port 5000, and a message is logged to the console indicating that the server is running.

This code provides a basic API for managing tasks, including creating, retrieving, updating, and deleting tasks. It utilizes Express for handling HTTP requests, MongoDB for data storage, and Mongoose for interacting with the MongoDB database.

Step 8: Implementing API Endpoint Logic
In the previous step, we added placeholders for the logic inside each API endpoint. Now, it's time to implement the functionality. Refer to the comments in the code for each endpoint to fill in the necessary logic.

Step 9: Starting the Server
Finally, start the Express server by adding the following code:

app.listen(5000, () => {
    console.log('Server is running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

This code starts the server on port 5000, and you'll see a message in the console confirming the server is running.

Conclusion:
Congratulations! You've completed the step-by-step tutorial on building a Task Manager API using Express. You've learned how to set up an Express application, connect to a MongoDB database, define a data model, and create API endpoints for managing tasks. This knowledge will empower you to build your own APIs and expand your skills in web development. Keep exploring and enhancing your Task Manager API to suit your specific project requirements. Happy coding!

Top comments (1)

Collapse
 
jonathanbolibenga01 profile image
jonathan

Merci pour la découverte et la prise en main avec express JS mais j'ai une surjection au niveau de la route app.post quand vous avez déclarer la variable : const {title, description} = req.body. Pouvez utiliser l'opérateur spread comme ceci ( ...req.body )mais merci j'ai aimé votre cours 👍🏻👍🏻👍🏻👌👌