How to Build a REST API

Now that we’ve reviewed all of the basics of what a REST API is and other fundamentals, it’s time to build one out. The example below shows a straightforward example of how to implement a REST API with NodeJS and Express. No actual CRUD operations are being done within the endpoints, but you can use this code to build those functionalities. Let’s start by setting up the environment, and then we will build out a few endpoints.

Step 1: Setting Up the Environment

  1. Install Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.
  2. Initialize Your Project:
    • Create a directory for your project.
    • Navigate to this directory in your command line and run npm init to create a package.json file.

Step 2: Installing Express

Since this API project will use Express, we must install it within our project using npm. To do this, run npm install express in your project directory. Once the command is complete, Express will be installed and ready for us to use.

Step 3: Creating Your Server (server.js)

Now, we will begin to implement the actual API code. First, we will need to set up the basic infrastructure for our app. The first step is to create a file named server.js and add the following code:

const express = require('express');
const app = express();
app.use(express.json()); // This middleware is used to parse JSON bodies.

app.listen(3000, () => console.log('Server running on port 3000'));

In the above code, we are doing the following:

  • require('express'): Imports the Express module.
  • express(): Initializes a new Express application.
  • app.use(express.json()): Middleware to parse JSON request bodies.
  • app.listen(...): Starts the server on port 3000.

If we were to run the app right now, our service would be able to start, but we would have no API endpoints for users to use. Next, we will focus on implementing some endpoints that users can leverage.

Step 4: Implementing RESTful Endpoints

When creating APIs, having multiple endpoints that achieve various tasks makes sense. We need to use the HTTP methods we covered earlier for CRUD APIs (like we will implement here). The methods include GET, POST, PUT, and DELETE; each corresponds with a different CRUD operation. Let’s look at an example of each type of endpoint below. This code can be added and executed within our Express project after the app.use() statement.

GET Endpoint

First, we will implement the GET endpoint that fetches data from the server. In the code below, you can see the basic structure of such an endpoint.

app.get('/api/items', (req, res) => {
  res.send('List of items');
});

In the app.get(...) statement, we define our GET route. When a GET request is made to /api/items, the callback function is executed. In the case above, we return a string using res.send(). In a more functional endpoint, you’d likely go off to some resource, such as a database, and return some data.

POST Endpoint

Next, we will implement the POST endpoint. This endpoint will contain the logic to add new data to the server. In the code below, you can see the structure of such an endpoint.

app.post('/api/items', (req, res) => {
  const newItem = req.body; // Data sent in the request body.
  res.send(`Item added: ${newItem.name}`);
});

In the code above, the app.post(...) function handles POST requests. The req.body contains the data sent in the request and is sent back in the response. In a more functional endpoint, you’d likely see logic here that would write some data to a resource, such as a database. Once a new record is created, you may send back a boolean, such as created: true or the ID of the newly created entity.

PUT Endpoint

Now, we will create the PUT endpoint that will update existing data. In the code below, you can see the basic structure of a PUT endpoint.

app.put('/api/items/:id', (req, res) => {
  const itemId = req.params.id; // Access URL parameter.
  res.send(`Item with ID ${itemId} updated`);
});

In the code above, you’ll see that the app.put(...) handles the PUT requests. The ID of the resource to update is often passed as a query parameter or URI parameter. To access this, in the code, we use req.params.id to fetch the id parameter from the URL. In a real-life implementation, you’d make a database call to update the resource, with data usually found in the request body, and then return a Boolean stating whether the update was processed.

DELETE Endpoint

Lastly, we will show an example of a DELETE endpoint that removes data from the server. The code below will show a basic example of what a DELETE endpoint would look like in Express.

app.delete('/api/items/:id', (req, res) => {
  const itemId = req.params.id;
  res.send(`Item with ID ${itemId} deleted`);
});

As you can see in the above code, the app.delete(...) method handles the DELETE requests. Like PUT, it uses req.params.id to determine which item to delete. Also similar to our other endpoints, this would likely make a request out to a database to delete the specified resource in a more functional application.

Step 5: Testing Your API

With our API built, our next step is to get it up and running on our local system and test it with Postman. Let’s look at the individual steps required to deploy and test our endpoints, starting with starting up our Node.js server.

Set Up and Run Your API

You must ensure your Node.js server is running to access your API endpoints. Usually, you’ll get your server up and running by executing a command such as node server.js in a terminal (pointing at the root of your project).

Configure Postman

Next, we need to download and install Postman (or Insomnia, if you prefer) to issue requests to our endpoints to test them.

First, install Postman. If you don’t already have it installed, download it from the official website. Once installed, you’ll want to create a request. To do this, open Postman, click “New”, then “Request”, and save it to a new or existing collection.

Test Your API Endpoints

We will issue a request for each endpoint with the appropriate method selected, such as GET, POST, PUT, or DELETE. Below are the specifics for each method type. To test GET: Select ‘GET’, input your endpoint (e.g., http://localhost:3000/api/items){:target=”_blank” rel=”noopener noreferrer”}, and click “Send” to view the response. To test POST: Switch to ‘POST’, add your data in the request body in JSON format, and send the request to check the response. To test PUT and DELETE: Repeat similar steps for PUT (to update data) and DELETE (to remove data), ensuring to include the item ID in the endpoint URL.

Analyze Responses

As you test each endpoint, check that the responses for each request in Postman are correct. Successful operations typically return status codes like 200 (OK) or 201 (Created). If there are errors, use the response details and your server console logs to debug. If your endpoints are changing resources in a database, you’ll also want to check that the correct actions have occurred there.


Comments

Leave a Reply

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