Tech

How to Build a Simple REST API with Node.js and Express

Creating a RESTful API is an essential skill for any developer working on web applications. A RESTful API provides a set of endpoints that can be accessed by clients to retrieve or manipulate data. In this article, we will walk you through the process of building a simple REST API using Node.js and Express, a popular web framework for Node.js.

Prerequisites

Before we start, make sure you have the following installed on your system:

  • Node.js
  • npm (Node.js package manager)

You can download and install Node.js from the official website: https://nodejs.org/en/download/

Setting Up the Project

  1. Open your terminal and create a new directory for your project:
mkdir simple-rest-api
cd simple-rest-api
  1. Initialize a new Node.js project by running the following command:
npm init -y

This will create a package.json file with default settings.

  1. Install Express and other required dependencies:
npm install express body-parser cors

We’ll be using body-parser to parse incoming request bodies and cors to handle Cross-Origin Resource Sharing (CORS) issues.

  1. Create a new file named app.js in your project directory. This file will contain the main logic for our API.

Implementing the API

Now that we have set up the project, let’s start implementing the API.

1. Importing Dependencies

First, open the app.js file and import the required dependencies:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

2. Creating the Express App

Next, create an instance of the Express application:

const app = express();

3. Configuring Middleware

We need to configure the middleware to parse JSON request bodies and handle CORS issues:

app.use(bodyParser.json());
app.use(cors());

4. Defining Routes

Now, let’s define the routes for our API. For this example, we’ll create a simple /users endpoint that allows us to retrieve a list of users, create a new user, and update an existing user.

First, create a new file named users.js in the routes directory:

mkdir routes
touch routes/users.js

Open the users.js file and add the following code:

const express = require('express');
const router = express.Router();

let users = [];

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

// Add a new user
router.post('/', (req, res) => {
  const { name, age } = req.body;
  const newUser = { name, age };
  users.push(newUser);
  res.status(201).json(newUser);
});

// Update a user by ID
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { name, age } = req.body;

  if (!users[id]) {
    return res.status(404).json({ message: 'User not found' });
  }

  users[id] = { name, age };
  res.json(users[id]);
});

module.exports = router;

In this code, we create an in-memory array to store the users. The /users endpoint has three methods: GETPOST, and PUT.

  • The GET method returns the list of users.
  • The POST method creates a new user and returns the created user.
  • The PUT method updates an existing user by ID and returns the updated user.

Now, back in the app.js file, import the users router and use it for the /users endpoint:

const usersRouter = require('./routes/users');

app.use('/users', usersRouter);

5. Starting the Server

Finally, we need to start the server and listen on a specific port (e.g., 3000):

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Now, if you run your application using node app.js, it should start the server and display a message indicating the port it’s running on.

Testing the API

To test the API, you can use a tool like Postman or make requests using the command line with tools like curl or httpie.

Here’s an example of how you can test the API using curl:

1. Get all users

curl -X GET http://localhost:3000/users

This should return an empty array since we haven’t added any users yet.

2. Add a new user

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "age": 30}' http://localhost:3000/users

This will create a new user and return the created user.

3. Update a user

curl -X PUT -H "Content-Type: application/json" -d '{"name": "Jane Doe", "age": 28}' http://localhost:3000/users/0

This will update the first user (assuming there’s only one user) and return the updated user.

Conclusion

In this article, we’ve learned how to build a simple REST API using Node.js and Express. We’ve covered the basic steps of setting up the project, configuring the middleware, defining routes, and testing the API. With this knowledge, you should be able to create your own RESTful APIs for various web applications.

Remember to expand on this example by adding more endpoints, implementing authentication, and using a database to store data persistently. Happy coding!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button