Creating Rest APIs Using Express

Pankaj Panigrahi
Better Programming
Published in
5 min readJan 9, 2019

This is the fourth piece of a series aimed at helping you grasp the different concepts behind Node.js and empowering you to create production-ready applications.

For this piece, we will be using one of the most popular libraries, Express, to build rest APIs. We are assuming the reader is familiar with Babel. If you are not, please read this article to familiarize yourself!

Getting Started With Express

Express is one of the most popular lightweight web application frameworks for Node and helps you respond to requests with route support so that you may write responses to specific URLs. It is one of the simplest and most versatile libraries.

To begin, install Express in your repo:

npm i express --save

Next, create an app.js file with the following lines of code:

import express from 'express';
let app = express();

This will import Express and instantiate the Express object.

We will be using the express.get() method, which routes HTTP get requests to the specified path with the specified callback functions.

app.get(path, callback [, callback …])

path: The path for which the middleware function is invoked.

calllback: Middleware function or array of middleware functions

You can read more about Express APIs here: http://expressjs.com/en/4x/api.html

Building the Foundation

After the first two lines, write the following code:

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. It represents the HTTP response that an Express app sends when it gets an HTTP request.

res gives us two methods of status() and send() which can be chained and used as above. status() is used to set the HTTP code of the response. send() sets the response body and close the response stream.

We will then use app.listen():

app.listen(path, [callback])

This starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s http.Server.listen().

app.listen(30006,()=>{
console.log(' ********** : running on 30006');
})

Now that we have used some ES6 syntax, let’s export this file as a module and call it in our index.js file. The entire code of app.js should look like below:

Next, create an index.js file:

And run the project using node index.js:

Implementing Routes

Let’s learn how to use app.use() & app.route().

app.use([path,] callback [, callback…]) mounts the specified middleware function or functions at the specified path. The function is executed when the base of the requested path matches path. Remember that path is optional here.

Mounting a middleware function is one of the best features of Express and gives us a lot of power & flexibility.

We will be using another popular library body-parser, It is the Node.js body parsing middleware. It parses incoming request bodies in a middleware before your handlers, available under the req.body property.

Let us install the module ‘body-parser’ and import it in our code

import bodyParser from 'body-parser';

Later in this piece, we will create an API which takes JSON data as input. We can enable all our APIs to parse JSON data by mounting APIs provided by body-parser as below:

Like app.get(), we have other methods like app.post() and app.put(). Then why do we need routes?

We can write all our APIs using app.get() or app.post(), but in order to avoid duplicate paths or typos and to modularize our code, we use routes.

We can write Express routes like below:

In the above implementation, any get request coming to the ‘/events’ URL will be handled by the ‘Handler 1’ middleware function and any post request coming to the ‘/events’ URL will be handled by ‘Handler 2’.

But there is a better way to implement routes using router & app.use().

A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application” capable only of performing middleware and routing functions. Every Express application has a built-in app router.

A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.

The top-level express object has a router() method that creates a new router object.

Creating Rest APIs

Let us create a route which will perform user-specific tasks for us.

Start by creating a folder routes and a file inside the same folder with the name user.js.

We can get the router instance with:

Then add the following code:

Here we are using the post() method of router to handle a post request to the specified path. We will be taking the user input from the req.body object and then sending the response. The module will be exported and used in our app.js.

So our final code of routes/user.js should look like this:

Now, import the module in our app.js:

import user from './routes/user';

As mentioned earlier, router behaves like middleware itself, so you can use it as an argument to app.use(). Let us mount our router to the path ‘/user’:

app.use('/user',user);

Our app.js should look like this:

The middleware function we wrote will handle all POST requests to the path ‘/user/hello’.

Restart the app and hit the API using POSTMAN.

We will be sent the data as a JSON input. Our code is able to parse it as we had mounted the following:

app.use(bodyParser.json())

Just to confirm our understanding, let’s comment that line as below:

//app.use(bodyParser.json())

Once again, restart and hit the API through POSTMAN.

As you can see, our code was unable to get req.body.username and instead, we received undefined in the response.

Conclusion

I hope this article helped you understand Express clearly. In later articles, we will see what we can do more with express.js.

You can find the code here:

https://github.com/pankaj805/medium-04_rest-api.git

Done for the day!

If you liked the article, you can 👏 the story and share it with others. You can find the entire article series here.

--

--

Responses (1)

What are your thoughts?