Friday 28 June 2013

Creating a REST API using Node.js, Express, and MongoDB




I recently used Node.js, Express, and MongoDB to rewrite a RESTful API I had previously written in Java and PHP with MySQL (Java versionPHP version), and I thought I’d share the experience…
Here is a quick guide showing how to build a RESTful API using Node.jsExpress, andMongoDB.

Installing Node.js

  1. Go to http://nodejs.org, and click the Install button.
  2. Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.
At this point node.js is ready to use. Let’s implement the webserver application from the nodejs.org home page. We will use it as a starting point for our project: a RESTful API to access data (retrieve, create, update, delete) in a wine cellar database.
  1. Create a folder named nodecellar anywhere on your file system.
  2. In the wincellar folder, create a file named server.js.
  3. Code server.js as follows:
We are now ready to start the server and test the application:
  1. To start the server, open a shell, cd to your nodecellar directory, and start your server as follows:
    node server.js
  2. To test the application, open a browser and access http://localhost:3000.

Installing Express

Express is a lightweight node.js web application framework. It provides the basic HTTP infrastructure that makes it easy to create REST APIs.
To install Express in the nodecellar application:
  1. In the nodecellar folder, create a file named package.json defined as follows:
  2. Open a shell, cd to the nodecellar directory, and execute the following command to install the express module.
    npm install
    node_modules folder is created in the nodecellar folder, and the Express module is installed in a subfolder of node_modules.
Now that Express is installed, we can stub a basic REST API for the nodecellar application:
  1. Open server.js and replace its content as follows:
  2. Stop (CTRL+C) and restart the server:
    node server
  3. To test the API, open a browser and access the following URLs:
    Get all the wines in the database:http://localhost:3000/wines
    Get wine with a specific id (for example: 1):http://localhost:3000/wines/1

Using Node.js Modules

In a large application, things could easily get out of control if we keep adding code to a single JavaScript file (server.js). Let’s move the wine-related code in a wines module that we then declare as a dependency in server.js.
  1. In the nodecellar folder, create a subfolder called routes.
  2. In the routes folder create a file named wines.js and defined as follows:
  3. Modify server.js as follows to delegate the routes implementation to the wines module:
  4. Restart the server and test the APIs:
    Get all the wines in the database:http://localhost:3000/wines
    Get wine with a specific id (for example: 1):http://localhost:3000/wines/1
The next step is to replace the placeholder data with actual data from a MongoDB database.

Installing MongoDB

To install MongoDB on your specific platform, refer to the MongoDB QuickStart. Here are some quick steps to install MongoDB on a Mac:
  1. Open a terminal window and type the following command to download the latest release:
    curl http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.2.0.tgz > ~/Downloads/mongo.tgz
    Note: You may need to adjust the version number. 2.2.0 is the latest production version at the time of this writing.
  2. Extract the files from the mongo.tgz archive:
    cd ~/Downloads
    tar -zxvf mongo.tgz
  3. Move the mongo folder to /usr/local (or another folder according to your personal preferences):
    sudo mv -n mongodb-osx-x86_64-2.2.0/ /usr/local/
  4. (Optional) Create a symbolic link to make it easier to access:
    sudo ln -s /usr/local/mongodb-osx-x86_64-2.2.0 /usr/local/mongodb
  5. Create a folder for MongoDB’s data and set the appropriate permissions:
    sudo mkdir -p /data/db
    sudo chown `id -u` /data/db
  6. Start mongodb
    cd /usr/local/mongodb
    ./bin/mongod
  7. You can also open the MongoDB Interactive Shell in another terminal window to interact with your database using a command line interface.
    cd /usr/local/mongodb
    ./bin/mongo
    Refer to the MongoDB Interactive Shell documentation for more information.

Installing the MongoDB Driver for Node.js

There are different solutions offering different levels of abstraction to access MongoDB from Node.js (For example, Mongoose and Mongolia). A comparaison of these solutions is beyond the scope of this article. In this, guide we use the native Node.js driver.
To install the the native Node.js driver, open a terminal window, cd to your nodecellar folder, and execute the following command:
npm install mongodb

Implementing the REST API

The full REST API for the nodecellar application consists of the following methods:
MethodURLAction
GET/winesRetrieve all wines
GET/wines/5069b47aa892630aae000001Retrieve the wine with the specified _id
POST/winesAdd a new wine
PUT/wines/5069b47aa892630aae000001Update wine with the specified _id
DELETE/wines/5069b47aa892630aae000001Delete the wine with the specified _id
To implement all the routes required by the API, modify server.js as follows:
To provide the data access logic for each route, modify wines.js as follows:
Restart the server to test the API.

Testing the API using cURL

If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, you could try:
You will only be able to test your GET services that way. A more versatile solution to test RESTful services is to use cURL, a command line utility for transferring data with URL syntax.
For example, using cURL, you can test the Wine Cellar API with the following commands:
  • Get all wines:
    curl -i -X GET http://localhost:3000/wines
  • Get wine with _id value of 5069b47aa892630aae000007 (use a value that exists in your database):
    curl -i -X GET http://localhost:3000/wines/5069b47aa892630aae000007
  • Delete wine with _id value of 5069b47aa892630aae000007:
    curl -i -X DELETE http://localhost:3000/wines/5069b47aa892630aae000007
  • Add a new wine:
    curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "New Wine", "year": "2009"}' http://localhost:3000/wines
  • Modify wine with _id value of 5069b47aa892630aae000007:
    curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "New Wine", "year": "2010"}' http://localhost:3000/wines/5069b47aa892630aae000007

Next Steps

In my next post, I’ll share a client application that makes use of that API. Update: The “next post” is now available here.

No comments:

Post a Comment