How to build a REST API in JavaScript

How to build a REST API in JavaScript

·

5 min read

Building a REST API can be a complex and daunting task, but with the right tools and knowledge, it can be done with relative ease. In this blog, we will explore the process of building a REST API with JavaScript, from scratch.

What is a REST API?

A REST (Representational State Transfer) API is a type of web service that is used to allow communication between different software systems. REST APIs are stateless, meaning that each request from the client to the server contains all the necessary information for the server to understand and respond to the request.

REST APIs are designed to be simple, flexible, and scalable. They allow developers to create web services that can be easily consumed by other applications, regardless of the programming language or platform used.

Requirements:

  • Make sure Node.js is installed

  • Make sure you have a code editor, I use VSCode.

Creating a New Project

The first step in building a REST API with JavaScript is to create a new project. Open up your code editor and create a new folder for your project. In this folder, create a new file called index.js. This file will serve as the entry point for our application.

To get started, we need to install a few dependencies. Open up a terminal window and navigate to your project folder. Then, run the following command:

npm init -y

This will create a new package.json file in your project folder. This file will contain information about your project, including its name, version, and dependencies.

Next, we need to install the following dependencies:

  • express

  • body-parser

  • nodemon

We can install these dependencies by running the following command:

npm install express body-parser nodemon --save

Express is a popular web framework for Node.js that makes it easy to build web applications. Body-parser is a middleware that is used to parse incoming request bodies in a middleware before your handlers. Nodemon is a utility that will monitor for any changes in your source code and automatically restart your server.

Building the API

Now that we have our project set up and our dependencies installed, we can start building our REST API.

First, let's open up the index.js file and add the following code:

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

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

This code sets up an Express application, adds body-parser middleware, and defines a simple route that sends a "Hello World!" message to the client when the root URL is requested. It also starts the server and listens on port 3000.

We can test our API by running the following command in the terminal:

nodemon index.js

This will start the server and listen for incoming requests. Open up a web browser and navigate to localhost:3000. You should see the "Hello World!" message.

Create the API Routes

Now that we have a working Express server, we can start defining the routes for our REST API. To do this, we need to create a new file called routes.js inside the src folder.

In routes.js, we will define the endpoints for our REST API. Let's start with a simple endpoint that returns a list of users. Add the following code to routes.js:

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

const users = [
  { id: 1, name: 'John Doe', email: 'johndoe@example.com' },
  { id: 2, name: 'Jane Doe', email: 'janedoe@example.com' },
];
router.get('/users', (req, res) => {
  res.json(users);
});
module.exports = router;

In this code, we create a new Express router instance and define an array of users with their names and email addresses. We then define a GET route for the /users endpoint that simply returns the users array as a JSON response.

We also export the router instance so we can use it in our main index.js file later.

Now, let's add a route to create a new user. Add the following code to routes.js:

let nextUserId = 3;

router.post('/users', (req, res) => {
  const newUser = { id: nextUserId++, ...req.body };
  users.push(newUser);
  res.json(newUser);
});

In this code, we create a new POST route for the /users endpoint that expects a JSON request body with a name and email property. We then create a new user object with a unique ID and the provided name and email, and add it to the users array. Finally, we return the new user object as a JSON response.

Now that we have defined the routes for our REST API, let's move on to the next step.

Testing the API Endpoints

Before we can deploy our REST API, we need to test the endpoints to make sure they work as expected. To do this, we will use a tool called Postman.

First, start the server by running the following command in the terminal:

npm start

Next, open Postman and create a new request by clicking on the + button in the top left corner. Select GET as the request method and enter the URL http://localhost:3000/users in the address bar. Click on the Send button to send the request.

You should see a JSON response with a list of users that we defined earlier.

Next, create a new request by clicking on the + button again. This time, select POST as the request method and enter the URL http://localhost:3000/users in the address bar. Select the Body tab, select raw and JSON as the input type, and enter the following JSON object in the request body:

{
  "name": "Sara Smith",
  "email": "sarasmith@example.com"
}

Click on the Send button to send the request. You should see a JSON response with the new user object that we just created.

Congratulations! You have successfully built a REST API with JavaScript using Express.

Conclusion:

In this blog, we learned how to build a RESTful API with JavaScript and Express. We covered the basics of REST, created routes for handling HTTP requests, and interacted with a database using Sequelize. With the knowledge gained from this blog, you can create your REST APIs using JavaScript and other related technologies.

Thank you for taking the time to read this blog. I hope it has been informative and has helped you gain a deeper understanding of the topic. If you have any feedback or suggestions for future content, please let me know!