Building a RESTful API with Node.js

Now that we have covered the basics of REST, let's put it into practice and build an API for OrderBase, which was constructed in the previous chapter. If you have not done so already, please take a moment to review the code that we wrote there in order to make sure that you understand what happens between our API and the database in this example.

Setting up the RESTful API

Start with creating a workspace for our server. On your drive, create a folder named order_api, step into this folder, and create and execute the file named api.js. Finally, open a terminal and execute the following:

npm init

As we saw in the previous chapter, this will give you a few questions to answer in order to bootstrap the Node.js server. When the questions ask you for the entry point, be sure to specify api.js, since this is the main file that your server configuration will be read from.

Next, you will need to import the database interface module that we created in Chapter 2, Configuring Persistence with MongoDB. To do so, first install the mongodb driver:

npm install mongodb

Then, you can import the module itself in two ways:

  • Copy and paste the database.js file from the previous chapter into the current directory and add var database = require('./database'); to the top of your api.js file
  • Add var database = require([pathToDatabase]) to the top of your api.js file, where [pathToDatabase] is the full system path to your database.js file

Once this is done, open the api.js file. Let's start adding some code for our API.

The HTTP module

The first thing we will need is a way to actually open up the Node.js instance to the network and enable it to communicate over the HTTP protocol, since this will be the core driver of our API's functionality.

In order to achieve this, we will include the standard HTTP module in our server. Add the following line to the top of your api.js file:

var http = require('http');

This will cause Node.js to load the HTTP module, a powerful component that can be used to listen for and process HTTP requests as well as send responses to the clients.

Now, with the module in place, let's hotwire Node.js to start listening and respond to simple HTTP requests. Add the following to your file:

var server = http.createServer(function (req, res) {
    res.writeHead(200);
    res.end("I am a fledgling API, and I am alright");
});
server.listen(8080);

console.log('Up, running and ready for action!');

That's it! If this is your first time using the HTTP module, you may be surprised at how simple this setup is. It is not everyday that you write a fully functioning HTTP server in seven lines of code! Node.js is just that good.

Let's give the server a run to make sure that it is working alright. Open your favorite browser and navigate to http://localhost:8080. You will see the following line of text:

I am a fledgling API, and I am alright

All is well. We are now ready to start making our API do something more interesting than just show the same text over and over. However, let's take a closer look first at how the HTTP module actually works and services requests.

Dissecting the HTTP server

Looking at our server code, we are really just doing the following two things:

  1. Configuring the event loop for our server is what it should do whenever an HTTP request comes in. This is done by invoking the http.createServer() method, which takes a callback function as a parameter, which will be executed for each incoming request.
  2. Bind the server to a given network port in the host machine and start listening for incoming connections on that port.

The interesting bit of the first item is the callback function:

function (req, res) {
  res.writeHead(200);
  res.end("I am a fledgling API, and I am alright");
}

This method takes two arguments, req and res. As you may have guessed, they refer to the HTTP request and the associated response. The req parameter will contain all the data associated with the incoming HTTP request, such as origin, headers, payload, cookies, and more. The res parameter is the HTTP response, which will be emitted back to the caller when the method is returned.

You may wonder why the response is passed as a parameter to a function that obviously handles incoming requests. This is a matter of design. The res parameter is actually created outside the function and passed to it so that you can do what modifications you see fit to it before the HTTP module takes control again, finalizes it, and sends it back to the sender.

In our function, we do only the following two things:

  • We set the response code of the response to 200, indicating a successful request cycle.
  • We append a string to the body (that is, the payload) of the response—"I am a fledgling API, and I am alright".

That's it as regards handling and responding to requests (really!).

Let's put this to use and start returning something more interesting.

Returning JSON

Normally, REST APIs will support serving data in several different formats, such as JSON and XML. For the sake of simplicity, we will only focus on JSON here. This makes sense in the context of what we have seen so far, where everything high and low is JavaScript - and JSON-oriented anyway.

Thankfully, returning a JSON object to our caller is almost trivial; we just need to make a few adjustments inside our callback function:

  • Specify the content type of the response as JSON
  • Convert the JSON object that we want to send back to a string

The first adjustment is done by modifying the Content-Type header of our response. In your code, you have the following code line:

res.writeHead(200);

You can change this to the following code line:

res.writeHead(200, {'Content-Type': 'application/json'});

This additional parameter, passed to the writeHead() method, is a JSON object with custom values for headers in the response object. If you don't specify headers, the HTTP module will generally set sensible defaults, but you should always be explicit when you are certain about what a header should be set to. Here, we want to make it clear to the client that we are sending them a JSON object as a response, and we set the Content-Type header accordingly.

To address the second item, let's first add a JSON object to send back to the client. After the res.writeHead() method, add the following:

var myProduct = {
  name: 'Apple',
  price: 600
};

Next, we need to turn this JSON object into a string in order to package it into the response. To do so, we can use the native Javascript JSON.stringify() method. As expected, this method takes a JSON object and returns a string representation of that object. Modify the following line:

res.end('I am a fledgling API, and I am alright');

Change the preceding line to the following:

res.end(JSON.stringify(myProduct));

We're done! Save your changes, restart the Node.js instance (just close and start it again), and refresh your browser window for the server. You will see the text:

{
  'name':'Apple',
  'price':600
}

We now have a full-fledged, JSON-serving HTTP server ticking. It's about time that we got down to the serious stuff.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122