Use Express to Build a REST API

An introduction to building scalable APIs in Node

Ferenc Almasi
Jan 16 · 7 min read
REST API created with Express in Node
REST API created with Express in Node
Photo by Clément H on Unsplash

Did you know that in 2019, Express ranked number one in awareness, interest, and satisfaction, according to State of JS, a yearly survey that had more than 20,000 respondents? It is mostly used to create robust APIs for the web quickly and easily through its flexible API.

APIs are common means of communication between different software components. They provide a simple way to exchange data between two application. In our case, this will be between the browser and a database. In this tutorial, we’re going to build a scalable REST API in Node using Express.

To keep things simple, we will go with the classical todo example. We will build an API to store, retrieve, modify and delete todo items. Each operation will be handled by a different HTTP request method. Our very first job will be to set up Express.


Setting Up Express

I also replaced the default script withnode server.js; this is the file where we will set up the Express server. Create the server.js file in your root directory and add the following lines to it:

We can start the webserver with app.listen passing in the port; either from the command line or defaulting to 8080. Not much is happening right now. If you open localhost:8080, you’ll see the server doesn’t return anything. So let’s change that and add some routes!

cannot get anything
cannot get anything

Creating Routes

  • GET for getting all or a single todo item
  • POST for creating a new todo item
  • PUT for updating an existing todo item
  • DELETE for removing a specific todo item

This is how our routes/index.js will look like:

routes will be a function that gets the express app as a parameter. The app variable exposes a route method which takes in an endpoint as a parameter. We can specify route params by using colons. By also adding a question mark at the end, we can tell express that this is only an optional param.

On route, we can chain different HTTP request methods. For every method, we will execute a different function. The methods are coming from an object defined in the controllers folder under Todo.js so that will be our next step.

But first, to actually tell Express to use these routes, go back to your server.js file and extend it with the following:

I’ve imported routes and passed the Express app to it. Now if you navigate to localhost:8080/todo it will call the todo.get method which we haven’t specified yet, so let’s do that right now.


Requests and Responses

Each method will get access to a request and response object. We also need to import the LocalStorage package since we’re going to use that in place of a real database. It will automatically create a db folder for you in the root directory.

Let’s go in order and see how we can get back todos using the get method.

Get route

To get URL parameters, we simply need to access the request.params object. The name of the property will be the one specified in app.route. (:id) To return a JSON response, we can call response.json with an object we want to return as a response:

If we don’t even have todos in localStorage, we can return an empty array. Otherwise, we can return the items stored in localStorage. Since we can only store strings, we need to call JSON.parse on the object. The same applies when we want to access a single todo. But this time, we also want to filter for a single item.

If you refresh the page, you’ll get back and empty todo list.

empty response coming back for get request
empty response coming back for get request

Post route

Open the app and create a new request. Set the method type to POST and the body to x-www-form-urlencoded. We only want to add a new todo if a name and a completed flag have been provided.

Sending a POST request from Postman
Sending a POST request from Postman

To get the values from the request inside Express, we can access request.body. If you, however, send a post request and try to log out request.body, you’ll notice that it is undefined. This is because express by default can’t handle URL encoded values. To make them accessible through JavaScript, we have to use a middleware. Add the following line to your server.js file, before you define the routes:

Now if you send the POST request and you try to log out request.body again, you’ll get the values logged out to your console.

Server linstening for POST request
Server linstening for POST request

So we can start by checking whether we have the two values in the request and if not, we can send an error specifying the problem:

The way we want to add a new item is we simply want to get the todos from localStorage if there’s any, parse the JSON and push a new object to the array. Then convert it back to JSON and of course, send a response to let us know if we were successful.

Note that since we might not have todos present in the localStorage, we need to fall back to an empty array. Also note that since we’re getting the requests as strings, we need to cast the completed flag to a boolean.

Adding new todos
Adding new todos

Put route

We want to follow a similar logic we did for the create method: Parse the localStorage data, update the item in the array where the id matches the one passed as a request param, convert the data back to JSON and send a success response:

Remember that we want to cast the completed flag into a boolean. And the reason why we can’t do logical OR just like we did for todo.name is because in case we want completed to be set to false, it would always fall back to the default todo.completed value.

Delete route

And reassign its stringified version back to todos inside localStorage.

deleting todo items
deleting todo items

Conclusion

If you were wondering about the look and feel of the JSON response I was getting throughout the tutorial, I’m using the JSON Viewer Chrome extension, which you can get at the provided link. If you would like to mess around with the final project, you can reach it at the express-api Github repo.

Thank you for reading through. Whether if you have any experience building APIs and working with Express or not, share your thoughts in the comments below and let us know what is your approach.

Better Programming

Advice for programmers.

Ferenc Almasi

Written by

Frontend dev with a passion for beautiful code and simple yet attractive designs. Get in touch by saying hello@allma.si or visit allma.si directly 👋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade