Building a Simple REST API with Node.js and Express
Tags: javascript, node
Published: 2020-11-04 13:45:38

In this article, we will build a simple REST API with Node.js and Express. I will not go deep on what REST APIs are, but I will try to help you answer this question throughout this article.

If you are someone who got used to working on the front-end, you probably noticed that there are things you simply can't implement in the front-end alone, such as authentication and interacting with a database.

This is where a REST API comes in. You can think of a REST API as a web service. It lets you implement certain features and functions in the back-end, which you can then access from the front-end with HTTP requests.

To further explain this idea, let's start with building our API by creating a directory for our project:
```sh
# create the directory
> mkdir hello-api
> cd hello-api
# setup a package.json file
> npm init
```
For those who are not yet familiar, `package.json` is a file that tells `npm` some information about our project, such as the dependencies we are using.

We then install Express (a JavaScript framework for building APIs with Node.js):

```sh
> npm install --save express
```

Let's create our first entry point called `index.js`:

```js
const express = require('express')

const app = express()

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

module.exports = app
```
Here, we simply imported `express` and created a variable called `app`. We are telling Node that `app` would be an Express app instance.

We are also telling Express to use `urlencoded` and `json` modules.

There are two common ways the front-end can pass data to an API. If you want to pass information from the front-end to the API, whether small or large, you will usually write and pass it to the API in JSON format (`application/json`). 

On the other hand, web forms (e.g. login forms) will usually have the content type `application/x-www-form-urlencoded`. For our Express app to be able to understand information with these types, we have to use the built-in `urlencoded` module.

We will also export `app` so we can interact with it from another script.

Now, the next thing we simply need to do is create a separate script to spin up our server. Create a script called `server.js`:

```js
const app = require('./index')

app.listen(3000, (err) => {
    if (err) throw err
    console.log('Server running in http://127.0.0.1:3000')
})
```

Now, let's run:

```
> node server.js
Server running in http://127.0.0.1:3000
```

So far, our API is running but it still does nothing.

## Middleware

The next thing we need to do is add functions or middleware to our API. Each middleware will consist of instructions that the API should follow and it is important that **our middleware should always return something**.

Let's say we have a restaurant called "Cheemsburbger" and we have customers who prefer to browse our website instead. However, our website has to be constantly updated and it should know if there is a food we can't serve for the day.

Let's create a middleware that will give our website an information about our menu. Create another directory inside `hello-api` called `services`. Let's create a service called `menu.service.js`:

```sh
> cd hello-api
> mkdir services
> cd services
```

```js
const express = require('express')

module.exports = {
    getMenu: (req, res) => {
        const menu = {
            'Number 9': 1.99,
            'Number 9 Large': 2.99,
            'Number 6 with Extra Dip': 3.25,
            'Number 7': 3.99,
            'Number 45': 3.45
        }

        return res.status(200).json({ menu: menu })
    }
}
```

What we did here is we created a function called `getMenu` and an object called `menu` which contains the food we can serve and their individual prices.

Remember that our middleware should always return something in the end. Most of the time, we will return an HTTP Status Code. This status code will tell a client (our front-end app) if the request is a success (200) or a failure (401 / 403 / 500). We are also returning a JSON which contains our `menu` object.

So the next time Big Smoke comes into our restaurant, we can tell him that we have everything except for the Large Soda which is not in our menu.

### `req` and `res`

You will notice that our function also has two parameters: `req` and `res`. This is a shorthand for `request` and `response`. `req` is the Express way of accessing information sent with the client's request, and `res` is the Express way of responding to that request.

## Route

We already have a middleware, but our clients (front-end app) will have no way to invoke it. We need to expose this middleware by specifying an endpoint or route.

**What's an endpoint and how do we invoke a middleware?**

We know that our app runs at `http://127.0.0.1:3000`. We want to tell Express that we want to expose `menu.service.js` through an endpoint called `/menu`. In this way, our client can request for our menu by performing a request on `http://127.0.0.1:3000/menu`.

Let's create another folder from our project's root directory called `routes` and create a script called `menu.js` inside it:
```sh
> cd hello-api
> mkdir routes
> cd routes
```

**menu.js**

```js
const express = require('express')
const router = express.Router()

const menuService = require('../services/menu.service')

router.get('/', menuService.getMenu)

module.exports = router
```

We first imported our menu service and created a route that will handle `GET` requests.

Remember that in the HTTP realm, requests can be made in different methods such as `GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. Here we will just demonstrate `GET`.

Let's modify our `index.js` for a bit and add a `/menu` route:

```js
const menu = require('./routes/menu')
app.use('/menu', menu)
```

We created an endpoint here called `/menu` which will use the routes we specified earlier. Now if someone makes a request to `http://127.0.0.1:3000/menu`, our API can respond to the request according to the HTTP method of that request. In this case, our API can handle `GET` requests to our `/menu` endpoint.

Let's run our API again:

```sh
> node server.js
```

You can test this with a web browser or cURL by making a GET request on our `/menu` endpoint:

```sh
> curl http://127.0.0.1:3000/menu
```

And that's it. There's still a lot to learn about building APIs with Express, but I hope this article helped explain the basics.

You can find the source code for this tutorial on [GitHub](https://github.com/starkfire/cheemsburbger-api).