Site icon DataFlair

ExpressJS Rest API

expressjs restful apis

Expert-led Online Courses: Elevate Your Skills, Get ready for Future - Enroll Now!

Express.js is a web framework for Node.js that allows developers to build web applications quickly. One of the most common use cases for Express.js is building RESTful APIs. In this article, we will take a closer look at what REST API is and how to build it using ExpressJS.

What is a REST API?

REST stands for Representational State Transfer, and it is an architectural style for building web services. RESTful APIs are a way of building web services that adhere to the principles of REST. A RESTful API is an API that uses HTTP methods like GET, POST, PUT, and DELETE to manipulate resources. The resources are identified by URIs, and the API uses HTTP status codes to communicate the results of each request.

Building a REST API with ExpressJS

Building a RESTful API with Express.js is relatively straightforward. You will need to define routes for each of the HTTP methods you want to support (GET, POST, PUT, DELETE). You will also need to define a schema for your resources, so you can validate input and output.

Example of how to build a simple RESTful API using Express.js:

const express = require('express');
const app = express();
const port = 3000;

const users = [
    { id: 1, name: DataFlair},
    { id: 2, name: Mehul},
    { id: 3, name: ExpressJS},
];

app.use(express.json());

app.get('/users', (req, res) => {
    res.json(users);
});

app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) {
        return res.status(404).send('User not found');
    }
    res.json(user);
});

app.post('/users', (req, res) => {
    const { name } = req.body;
    if (!name) {
        return res.status(400).send('Name is required');
    }
    const user = {
        id: users.length + 1,
        name,
    };
    users.push(user);
    res.json(user);
});

app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) {
        return res.status(404).send('User not found');
    }
    const { name } = req.body;
    if (!name) {
        return res.status(400).send('Name is required');
    }
    user.name = name;
    res.json(user);
});

app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) {
        return res.status(404).send('User not found');
    }
    users.splice(userIndex, 1);
    res.sendStatus(204);
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

In this example, we define an array of users and create routes for each of the HTTP methods. We use the json middleware to parse JSON input, and we use HTTP status codes to communicate the results of each request. We also validate input and output using simple schema validation.

Defining Routes in ExpressJS

When building a RESTful API with Express.js, defining routes is an essential part of the process. Routes define the endpoints for your API and specify the HTTP methods that are allowed for each endpoint. In the previous example, we defined routes for the /users endpoint using the app.get, app.post, app.put, and app.delete methods.

The app.get method specifies that the endpoint should respond to HTTP GET requests, while the app.post method specifies that the endpoint should respond to HTTP POST requests, and so on. You can also use the app.all method to define a route that responds to all HTTP methods.

Parsing JSON

In the previous example, we used the json middleware to parse JSON input. The json middleware is included in Express.js by default, and it can be used to parse incoming JSON data from requests automatically. To use the json middleware, you simply need to call app.use(express.json()) at the top of your application code.

Validation

When building a RESTful API, it’s essential to validate input and output to ensure that your API is secure and reliable. In the previous example, we used simple schema validation to validate the input and output of each endpoint.

Testing

Testing your RESTful API is an important part of the development process. There are many tools available for testing RESTful APIs, including Postman, curl, and Jest.

Postman is a popular tool for testing RESTful APIs that provides a GUI for making HTTP requests and inspecting the responses. curl is a command-line tool that can be used to make HTTP requests from the command line. Jest is a testing framework that provides a suite of tools for testing Node.js applications, including RESTful APIs.

Conclusion

Building a RESTful API with Express.js is a powerful way to expose your data and services to other applications. By defining routes, parsing JSON, validating input and output, and testing your API, you can create a reliable and secure API that is easy to use and understand. With the help of Express.js, building a RESTful API is a straightforward process that can be accomplished with just a few lines of code.

Exit mobile version