Course site

IE 2 - My First ReSt API

This assignment aims to walk you through building your first REST API as part of your backend component. In the end, you’ll have a chance to evolve this code by yourself. Use it to self-assess if you need further study on this matter or seek help.

We’ll build our backend in JavaScript (Node.js) with a framework called Express - Node.js web application framework. Express is a lightweight web development framework that makes it straightforward to build REST APIs for web applications and beyond.

Preparation - Create a new branch and package for this assignment

  1. You just turned in your first assignment for grading, and you want to make be sure that any work you do here doesn’t break the first assignment. To make sure this doesn’t happen, you’ll want to start this new assignment on a branch. So, before making any changes, create a new branch and then switch to that branch. For example, if you call your new branch backend, you’d run the command:
git status
git checkout -b backend
  1. Now, you’ll need to create a new folder (e.g. express-backend) in packages where you will develop the backend. You do not need to initialize this folder with git (DON’T run git init command in the folder) because it is inside the monorepo which we already initialized.

  2. There is nothing like create-react-app for express, so you will need to install all the dependences for expressjs-backend yourself. But you should keep these dependences separate from the frontend’s dependences. That is, even though you have a git monorepo, you want to maintain two independent npm packages.

To do this, run npm init from your express-backend folder. When you answer the questions this time, take the defaults for everything except use backend.js for the entry point (last option); index.js will work too, but calling it something else will avoid confusing it with the frontend’s index.js.

You may have noticed that running npm init creates a package.json file in that folder. This is how npm determines that it is the root of a package. The package.json file is important because it maintains a list of dependences—other packages like react and expressjs which are required by our code. If you look in the react-frontend folder you will also see a package.json, even though you never ran npm init there! The reason is that create-react-app ran npm init itself, and installed a bunch of dependences, which you can see by viewing the package.json.


0 - Installing Express.js

Now you are going to install express, and tell NPM that you want it to remember that this is a dependency of only the express-backend workspace. Run the command below from the root folderm(csc-307-app).

npm install -w express-backend express

Notice that we ran npm install with the -w express-backend option. Without this option, npm would add express as a global dependency of the entire project and put it in the top-level package.json. Instead, you can open package.json in packages/express-backend and verify that express is listed in the dependencies section.

For more information on installing Express, check out their official documentation.

Notice also that there is no node_modules directory in express-backend. Instead, npm maintains all the installed packages for all workspaces in the top-level node_modules directory. This allows it to share the installed packages across multiple workspaces without duplicating them.

1 - Creating a Hello World

Let’s first create a hello world in Express just to make sure we have all the environment set up to continue.

Continuing on the same folder from the previous step, create the main file for your backend service (your REST API). I named my main file backend.js (see the npm init step above). So I’ll create this file and open it on my code editor. If your main is index.js, proceed with creating this file accordingly.

A minimal Express application looks something like this:

// backend.js
import express from "express";

const app = express();
const port = 8000;

app.use(express.json());

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

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

So what does that code do?

First, we import the Express module. Express will work as an HTTP middleware dispatching HTTP calls to the routes we define in the file and also sending back responses that we’ll program.

Next, we create an instance of Express and define a constant to represent the port number we’ll use to listen to incoming HTTP requests.

On the fourth line, we set up our express app to process incoming data in JSON format. With that, Express (as a middleware) will allow us to access JSON data seamlessly in memory.

Then, we set up our first API endpoint with the app.get function. This sets the endpoint to accept http GET requests. And the app.get has two arguments. First, / is the URL pattern that will map to this endpoint. Second, we have the callback function that’ll be called when our server receives an incoming GET request matching the / URL pattern. This anonymous function receives two objects, one representing the request (req) and the other representing the response (res). Inside the function, we can use those objects to process the request and send a response to the client that called the REST API. For now, we just use the response object to send a plain-text message back.

Finally, we make our backend server listen to incoming http requests on the defined port number.

Notice we are using ES Module syntax:

import express from "express;

As mentioned in class, Node uses another module system, called CommonJS, by default. Since we want to use Modern Javascript for both frontend and backend, we need to tell NodeJS that backend.js (and anything it imports) is an ES module. So you need to add the following line to the package.json in the express-backend package (you can put it just before the "main": "backend.js" line):

  "type": "module",

Now you are are ready to run the application. Type the following command on the terminal:

node backend.js # or whatever filename you used

And you should see the following output on the terminal:

Example app listening at http://localhost:8000

Now head over to http://localhost:8000/, and you should see your hello world greeting since that represented a request to the ‘/’ (root) route of your backend.

If you get errors at this point, they will most likely be: (i) syntax errors on the JavaScript file; (ii) failure to install the express package or NodeJS environment. Make sure you double-check everything.

Before moving to the next step, make sure you add the files in your backend directory to Git and push the changes up to GitHub.

2 - Beyond the ‘/’ route

Our / route mapped to a simple “Hello World” text response. Still, it’s exposed as a REST API. Essentially, any application written in any language can make a GET HTTP request to your API endpoint and obtain the HTTP response with the Hello World message. Although this might not sound useful, the infrastructure is already set up, which is very helpful.

Let’s now make a new route to allow clients to retrieve a list of users. We’ll use the same kind of list we used in the React work on Week 1 (except that I added random IDs). Here’s the data structure to add to your JavaScript file:

// backend.js
......
const users = {
  users_list: [
    {
      id: "xyz789",
      name: "Charlie",
      job: "Janitor",
    },
    {
      id: "abc123",
      name: "Mac",
      job: "Bouncer",
    },
    {
      id: "ppp222",
      name: "Mac",
      job: "Professor",
    },
    {
      id: "yat999",
      name: "Dee",
      job: "Aspring actress",
    },
    {
      id: "zap555",
      name: "Dennis",
      job: "Bartender",
    },
  ],
};

Now, we’ll define the /users GET route which will return the entire list of users. Here’s the code to add to your JavaScript file after the code app.get("/", (req, res) => {.

// backend.js
app.get("/users", (req, res) => {
  res.send(users);
});

Now, head over to http://localhost:8000/users, and you should see the response content in JSON format. (If node backend.js is still running, you will need to stop it with Ctrl-C and restart it to load your changes.)

Remember to Git-commit your changes before continuing. Push changes to GitHub if you’ve already set up a remote repo there.

3 - Using nodemon to avoid having to restart the server manually

You probably noticed that you need to manually kill the server and restart it again every time you change the code. This is very inconvenient while you’re programming and making changes to your code constantly. So, we’ll install a package called ‘nodemon’ and use it to run our app backend to overcome this scenario. On the root of your project folder (so it will apply to every workspace), run:

npm install --save-dev nodemon

We’re using the --save-dev argument because this is a project dependency only needed in the development environment. This is not a necessary dependency at runtime. You can look at your package.json file and note a separate section for devDependencies.

Now, instead of running your backend app with ‘node’, we can run it with nodemon. Nodemon will execute node but beyond that, it’ll restart the server every time you save changes on the code.

npx nodemon backend.js

Now, make any change to your code and watch nodemon automatically restarting the server.

Another good practice is to edit the package.json file and add two new script targets for running the app. In your backend’s package.json file, the “scripts” section will look like this:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "npx nodemon backend.js",
  "start": "node backend.js"
},

Now, if you type in your console npm run dev you’ll run the backend app with nodemon. And if you type npm start you’ll use node. Typically, you use npm run dev while coding your backend, and npm start will be used when you want to run your app in the production environment. These changes won’t make much difference for now, but they will make much more sense when we start working with continuous integration & deployment. At least, this step helps you explore a bit more the package.json file and become more familiar with it.

Lastly, if you want debug information (like knowing when a GET, POST method is called in the backend), set a DEBUG environment variable which will tell node to print debug messages. For example, on a Mac/Linux you would type the following before starting nodemon/node.

export DEBUG='express:router'

For a windows machine (and to run the DEBUG with the npx all in one command)

$env:DEBUG='express:router'; npx nodemon backend.js

4 - Getting users by name

Suppose that, besides fetching all users, we want to retrieve users with a certain name. To do that, we do not need to create a new route. We can use HTTP query strings to pass a name as an argument through the API and access it in our /users GET endpoint. If our query argument is name, then we can access it calling req.query.['name'] or req.query.name.

In the browser (or in any other web client), the URL will be .../users?name=Mac where “Mac” is an example of a name I’m looking for.

Now that we know how to pass an HTTP query argument as part of a GET method, with a bit of logic we can find specific users with a given name to return in our get users endpoint. A possible solution for that is this one which replaced our previous /users route:

const findUserByName = (name) => {
  return users["users_list"].filter((user) => user["name"] === name);
};

app.get("/users", (req, res) => {
  const name = req.query.name;
  if (name != undefined) {
    let result = findUserByName(name);
    result = { users_list: result };
    res.send(result);
  } else {
    res.send(users);
  }
});

And Step 4 is done! On your browser, access http://localhost:8000/users?name=Mac, and you should see the response containing the two users with the name “Mac”. Take the chance to play around with different values for the query argument name.

Pssst…, Git-commit your changes…

5 - Getting users by ID

The way you define your API routes is relevant. A good practice is to avoid action names (e.g., get-users) when dealing with basic operations (create, retrieve, update, delete) over an entity-set of your application (in our case ‘users’). In our example, everything should be over the route /users or variations of it /users/<id>, which we’ll explore in this current step.

The reading that I already assigned to you should give you more background on web API design, including how you should name the API operations by properly using the http methods (GET, POST, PUT, DELETE, PATCH). It’s out of the scope of this assignment to discuss here everything on that reading, but it is equally important to do that reading.

In this step, we’ll address the /users/:id GET endpoint which should be used when we want to retrieve a specific user by the given id. Here, we’re assuming the id field uniquely identifies a user. Express allows you to use the : symbol to tag a variable that is part of the URL (don’t confuse this with query arguments explored in the previous step). This variable will be then passed to the endpoint function you create to handle the requests coming from that route. Since our route is /users/:id we’ll create a function accordingly.

With a bit of logic, we can find the right user with a given id. Otherwise, we respond with a 404 resource not found msg.

const findUserById = (id) =>
  users["users_list"].find((user) => user["id"] === id);

app.get("/users/:id", (req, res) => {
  const id = req.params["id"]; //or req.params.id
  let result = findUserById(id);
  if (result === undefined) {
    res.status(404).send("Resource not found.");
  } else {
    res.send(result);
  }
});

Like our previous route, this one uses a helper function to do the actual work. It’s a good idea to keep all the helper functions together in your file, and not interspersed with the routes. This will make it easier to refactor backend.js later.

Note that we used the JavaScript Array find() function for this specific intent instead of filter(). find() returns the first occurrence that matches the condition. Since we’re saying that id is a unique identifier, the find() function is the preferred solution.

Also, note the syntax to return a specific HTTP status code (we chose 404) along with a plain-text msg.

On your browser, access http://localhost:8000/users/zap555, and you should see only Dennis, the bartender. If it works, don’t forget to git commit before moving on…

6 - Using the POST method

With the previous endpoints, we’ve been reading from the backend. Now, consider we need to add a new user to the list of users. That’s our first ‘write’ operation.

Note: we’re working with data in memory, so our add operation will not be persistent. However, the API design is exactly the same if we would implement data persistence with a database.

Again, as I said in the previous step, the route is the same: /users. Don’t make a ‘/add-user’ route. Although that would work, we want to follow REST conventions when designing our APIs. So we’ll reuse the same URL pattern (/users) but now handling a different action since it’ll be a POST method. If the HTTP request comes in with a GET method, it will do what we already did in the previous step. But if the request comes with a POST method, we’ll accept the json data that comes in and use it to create a new object in the list.

Note: intentionally, we’re not doing data validation for the sake of simplicity. For beginners, there’s already a lot to bite in this work. If you feel it’s still too basic for you, take data validation as a stretch goal, think about what data validation you can implement on this endpoint, pick the right http status code for responding in case of invalid data, and go with it.

Express.js allows us to implement endpoints for any HTTP method (GET, POST, PATCH, PUT, DELETE, etc.). We’ve used GET, now we’ll use POST. For now, we won’t handle different HTTP codes and unsuccessful addition. Let’s just assume the data is in the right format and will always be inserted. Note in the code below how we send an empty response with a given HTTP code. 200 is the default response code but it was explicitly defined in the code below to show you how we can pass any HTTP code we want.

const addUser = (user) => {
  users["users_list"].push(user);
  return user;
};

app.post("/users", (req, res) => {
  const userToAdd = req.body;
  addUser(userToAdd);
  res.send();
});

Note how we can simply access the incoming data in the request as req.body.

To test this step, we have to make a POST call which can’t be done through the browser without an additional tool (since we need to attach a json object to be added once it gets through the API – our new user). There are several options to test our POST endpoint. One option is to install a browser add-on such as Boomerang for Chrome or Rested for Firefox and by using their user interface you can make API calls by attaching json objects manually. For instance, use this new json object to be added to the backend users list:

{
  "id": "qwe123",
  "job": "Zookeeper",
  "name": "Cindy"
}

Note the double-quotes. Even though JavaScript accepts single quotes besides double quotes (or no quotes at all for the keys in the key-value pairs), the outside world does not know you’re implementing your backend in JavaScript. Besides, we have to follow the JSON standard, which specifies double quotes. Express will throw a 400 bad request if you pass the JSON object with single quotes.

Besides using browser add-ons, another option is to install a command line tool called curl. With curl, you can make all sorts of API calls in the console text interface. Finally, you can also use more robust and complete API dev tools such as Postman.

Once you make the POST call, to finally add a new user to the list, you can make a fetch call and see your recent user added to the list.

Don’t forget to git-commit current changes. If you haven’t pushed to a remote server, it’s also a good time to do it. If you’re not sure or don’t remember how to do it, refer to the React first app - Part II (Individual Assignment), where we did all that.

For more documentation and tutorials around Express, go to expressjs.com.

7 - Now evolve the code by yourself

With what we’ve produced so far, you should be able to evolve the code by yourself. Here I have two tasks for you:

First, implement a hard delete operation to remove a particular user by id from the list. Hint: look at another HTTP method called DELETE. And remember this: always try to reuse existing URL patterns. Don’t implement a route called ‘/delete-user’. Look at the resource you want to access and perform the delete action (you may have a URL pattern for it already).

Second, implement an additional action to get all users that match a given name and a given job. Hint: look at what we did in step 4 and extend it.

Don’t forget to commit and push your code.

Have fun with Express and Node.js!

I want to make one change.