Create REST API and test its routes

This exercise demonstrates how to create a REST API and test it routes.

Objective

Create and test the REST API route for the customer resource

Description

A REST (REpresentational State Transfer) API allows the exchange of data in a simple way, without the need for clients to know any detail about the server. The client only needs to know where the resource is (the URL), and the action it wants to perform on it.

Create an API route that responds with JSON at the root path “/”.

Build routes that support: GET request to get a list of all customers, POST request to add a new customer.

You can retrieve or update the information of an individual customer stored in the database usually by its unique id. One possible way to achieve this is by attaching using the id in the route parameters. Route parameters are named segments of the URL, delimited by slashes (/). Each segment captures the value of the part of the URL which matches its position. The captured values can be found in the req.params object.

You should also target individual customers by ID and get information about that customer by GET request. PATCH request should be used to update the customer’s information, and DELETE request to delete the customer from the database.

This exercise is just to create the routes and test them in an app such as Postman. We will not be creating or updating an actual customer in this exercise.

Create the following routes that should handle the following requests:

  • GET: / – Handle GET request

  • POST: / – Create a new customer

  • GET: /:id – fetch a customer with an id.

  • PATCH: /:id – update a customer with an id

  • DELETE: /:id – delete a customer with an id.

 

Tasks

  • GET request to the / route (ex. http://locahost:9001/) should serve the object:
{
  "message": "Customers were fetched"
}

 

  • GET request to the /2584 route (ex. http://locahost:9001/2584) should serve the object:
     {
       "message": "Customer with id 2584 was fetched"
      }
    

    Where 2584 is the id of the customer, and is passed as a route parameter.

 

  • POST request to the / route should serve the object:

    {
      "message": "New customer added"
    }
    
  • PATCH request to the /2584 route should serve the object:

    {
      "message": "Customer's information for id- 2584 updated"
    }
    

 

  • DELETE request to the /2584 route should serve the object:
    {
      "message": "Customer with id 2584 deleted"
    }
    

Hints

  • Install express.js

    npm i express

 

  • Require express and execute express() like a function which will spin up an express application. Save this in a constant variable.

    const express = require(‘express’);
    
    const app = express();

 

  • Create a method app.listen(portNumber), which will tell the server to listen on a given port.

 

  • You can build a GET endpoint using app.get(…) in express.

    Similarly you can create a POST request using app.post(…).

 

  • If you want to respond with a JSON object at / route, you can do so with:

    app.get("/", (req, res) => {
      res.json({
        message: "Hello",
      });
    });

    where req is the request object, and res is the response object

 

  • You can get the route parameter id from a route (eg: https://localhost:9001/2584) as follows:

    app.get("/:id", (req, res) => {
      var id = req.params.id;
    });

     

Solution


Edit create_and_test_api_routes

Solution Walkthrough

 

Introduction

As mentioned in the description, a REST API allows the exchange of data in a simple way, without the need for clients to know any detail about the server. The client only needs to know where the resource is (the URL), and the action it wants to perform on it.

REST API uses HTTP verbs like GETPUTPOST, and DELETE to access and manipulate data.

Here, we will be building a REST API using the following stack:

  • Node.js
  • Express
  • MongoDB and Mongoose

Project setup

Start by creating a new directory for the project. Since, we are building an API for customer resource let’s name it customer-api

mkdir customer-api

The move into this directory and scaffold a new project using the following npm command:

npm init

This creates a new file package.json . It holds project’s meta data such as name , description and it is used for managing the project’s dependencies, scripts, version.

Next install Express as a dependency.

npm i express

Express is framework for Nodejs that provides a robust set of features for developing web applications. Express has a variety of HTTP utility methods and middleware that helps to create a robust API quickly and easily.

Create a new file index.js in our folder, which will be the main entry point to our application.

Code walkthrough You can refer to the code from the GitHub repo or from playground.

Start off by requiring express in our index.js file and save it to a constant variable. Next execute express () like a function which will spin up an express application. Save this in another constant variable called app.

const express = require("express");
const app = express();

Define a port number and create a method app.listen(portNumber), This will tell the server to listen on a given port.

const port = 9001;

app.listen(port, () => console.log(`Listening on port ${port}`));

Next define routing using methods of the express object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post() to handle POST requests.

The following endpoint will listen to HTTP GET request at the / route and when when the route is accessed from the client it will respond with a message “Customers were fetched” .

app.get("/", (req, res) => {
  res.send({
    message: "Customers were fetched",
  });
});

To get the information of an individual customer from the database, the client must supply the id of customer. It is usually done by passing it as a route parameter in the url. Example endpoint: http://localhost:9001/2584. The code below uses req.params to get the route parameters from the endpoint and responds with a message.

app.get("/:customerId", (req, res) => {
  let customerId = req.params.customerId;

  res.send({
    message: `Customer with id ${customerId} was fetched`,
  });
});

Similarly create routes to handle POST, PATCH, DELETE requests.

app.post("/", (req, res) => {
  res.send({
    message: "New customer was added",
  });
});

app.patch("/:customerId", (req, res) => {
  let customerId = req.params.customerId;

  res.send({
    message: `Customer’s information for id ${customerId} was updated`,
  });
});

app.delete("/:customerId", (req, res) => {
  let customerId = req.params.customerId;

  res.send({
    message: `Customer with id ${customerId} was deleted`,
  });
});

Testing routes

We will first have to start our node app and send a request to one of the route that we defined to get a response.

Start the server with the following command:

node index.js

You should see the following message in your terminal

Listening on port 9001

This ensures that our server is up and running and ready to accept requests.

You can open another terminal and use curl to make an HTTP request to your server. Example:

curl http://localhost:9001/

This should respond with a following output:

{"message":"Customers were fetched"}

You can also make requests using a graphical HTTP client such as Postman. To test with Postman, enter the request URL, select an HTTP verb, enter body data (usually for POST, PATCH) requests, and click send.

Testing GET route

For example: Enter the URL http://localhost:9001/ and select GET and then click send.

test get API route

We get the exact message that we were expecting as a response.

Testing POST route

We can pass form-data or raw JSON while making a POST request.

Test POST API Route

Testing DELETE route

DELETE request expects a query parameter, so if you try without passing a parameter, you will get an error.

Delete route error

Now, let’s try again by passing a query parameter.

Delete route by passing route params

Test API DELETE route

It works this time!

We have now built basic routes for “GET”, “POST”, “PATCH”, and “DELETE”. In the coming exercises, we will make these routes functional by connecting to a database, and also refactor and organize the code in a better way!