DEV Community

Pocholo Pantoja
Pocholo Pantoja

Posted on

Building a Simple REST API with Node.js and Express

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:

# create the directory
> mkdir hello-api
> cd hello-api
# setup a package.json file
> npm init
Enter fullscreen mode Exit fullscreen mode

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):

> npm install --save express
Enter fullscreen mode Exit fullscreen mode

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

const express = require('express')

const app = express()

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

module.exports = app
Enter fullscreen mode Exit fullscreen mode

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:

const app = require('./index')

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

Now, let's run:

> node server.js
Server running in http://127.0.0.1:3000
Enter fullscreen mode Exit fullscreen mode

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:

> cd hello-api
> mkdir services
> cd services
Enter fullscreen mode Exit fullscreen mode
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 })
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

> cd hello-api
> mkdir routes
> cd routes
Enter fullscreen mode Exit fullscreen mode

menu.js

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

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

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

module.exports = router
Enter fullscreen mode Exit fullscreen mode

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:

const menu = require('./routes/menu')
app.use('/menu', menu)
Enter fullscreen mode Exit fullscreen mode

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:

> node server.js
Enter fullscreen mode Exit fullscreen mode

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

> curl http://127.0.0.1:3000/menu
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
talorlanczyk profile image
TalOrlanczyk

Great article!!
I think you miss in the middleware explanation about how to write a middleware with
(req, res, next) like an auth middleware that will prevent you from accessing the route middleware

Collapse
 
starkfire profile image
Pocholo Pantoja

Thank you for the feedback 😃

While writing the article, I was thinking of authentication as a good example to demonstrate next and the other concepts. However, I'm still trying to figure out how I can gradually turn this into a beginner-friendly tutorial series, so I might write a Part 2 and Part 3 for this.

Collapse
 
talorlanczyk profile image
TalOrlanczyk

If you need any help you can contact me I think I have good ideas for your series

Collapse
 
peculiarnoobie profile image
Joshua Ron Garcia

Hello this is my first time learning API. This is very educational.