Deploy Your Own REST API in 30 Mins Using mLab and Heroku

The MEAN stack is a popular web development stack made up of MongoDB, Express, AngularJS, and Node.js. MEAN has gained popularity because it allows developers to program in JavaScript on both the client and the server. The MEAN stack enables a perfect harmony of JavaScript Object Notation (JSON) development: MongoDB stores data in a JSON-like format, Express and Node.js facilitate easy JSON query creation, and AngularJS allows the client to seamlessly send and receive JSON documents.

MEAN is generally used to create browser-based web applications because AngularJS (client-side) and Express (server-side) are both frameworks for web apps. Another compelling use case for MEAN is the development of RESTful API servers. Creating RESTful API servers has become an increasingly important and common development task, as applications increasingly need to gracefully support a variety of end-user devices, such as mobile phones and tablets. This tutorial will demonstrate how to use the MEAN stack to rapidly create a RESTful API server.

--ADVERTISEMENT--

AngularJS, a client-side framework, is not a necessary component for creating an API server. You could also write an Android or iOS application that runs on top of the REST API. We include AngularJS in this tutorial to demonstrate how it allows us to quickly create a web application that runs on top of the API server.

The application we will develop in this tutorial is a basic contact management application that supports standard CRUD (Create, Read, Update, Delete) operations. First, we’ll create a RESTful API server to act as an interface for querying and persisting data in a MongoDB database. Then, we’ll leverage the API server to build an Angular-based web application that provides an interface for end users. Finally, we will deploy our app to Heroku.

So that we can focus on illustrating the fundamental structure of a MEAN application, we will deliberately omit common functionality such as authentication, access control, and robust data validation.

Source Code Structure

package.json — a configuration file that contains metadata about your application. When this file is present in the root directory of a project, Heroku will use the Node.js buildpack.

app.json — a manifest format for describing web apps. It declares environment variables, add-ons, and other information required to run an app on Heroku. It is required to create a “Deploy to Heroku” button.

server.js — this file contains all of our server-side code, which implements our REST API. It’s written in Node.js, using the Express framework and the MongoDB Node.js driver.

/public directory — this directory contains all of the client-side files which includes the AngularJS code.

See the Sample Application Running

Create a New App

Create a new directory for your app and use the cd command to navigate to that directory. From this directory, we’ll create an app on Heroku which prepares Heroku to receive your source code. We’ll use the Heroku CLI to get started.

When you create an app, a git remote (called heroku) is also created and associated with your local git repository. Heroku also generates a random name (in this case sleepy-citadel-45065) for your app.

Heroku recognizes an app as Node.js by the existence of a package.json file in the root directory. Create a file called package.json and copy the following into it:

The package.json file determines the version of Node.js that will be used to run your application on Heroku, as well as the dependencies that should be installed with your application. When an app is deployed, Heroku reads this file and installs the appropriate Node.js version together with the dependencies using the npm install command.

To prepare your system for running the app locally, run this command in your local directory to install the dependencies:

$ npm install

After dependencies are installed, you will be ready to run your app locally.

Provision a MongoDB Database

After you set up your application and file directory, create a MongoDB instance to persist your application’s data. We’ll use the mLab hosted database, a fully managed MongoDB service, to easily provision a new MongoDB database:

When you create a mLab database, you will be given a MongoDB connection string. This string contains the credentials to access your database, so it’s best practice to store the value in a config variable. Let’s go ahead and store the connection string in a config var called MONGODB_URI:

You can access this variable in Node.js as process.env.MONGODB_URI, which we will do later.

Now that our database is ready, we can start coding.

Connect MongoDB and the App Server Using the Node.js Driver

There are two popular MongoDB drivers that Node.js developers use: the official Node.js driver and an object document mapper called Mongoose that wraps the Node.js driver (similar to a SQL ORM). Both have their advantages, but for this example we will use the official Node.js driver.

Create a file called server.js. In this file we’ll create a new Express application and connect to our mLab database.

We want to use our database connection pool as often as possible to best manage our available resources. We initialize the db variable in the global scope so that the connection can be used by all the route handlers.

We initialize the app only after the database connection is ready. This ensures that the application won’t crash or error out by trying database operations before the connection is established.

Now our app and database are connected. Next we will implement the RESTful API server by first defining all the endpoints.

Create a RESTful API Server with Node.js and Express

As our first step in creating the API, we define the endpoints (or data) we want to expose. Our contact list app will allow users to perform CRUD operations on their contacts.

We haven’t created our web app yet, but you can confirm that the data was successfully saved to the database by visiting the mLab management portal. Your new contact should be displayed in the “contacts” collection.

Alternatively, you can visit https://mlab.com/databases/your-db-name/collections/contacts and observe your new contact there.

Here is the final version of the server.js file, which implements all of the endpoints:

Set up Static Files for the Web App

Now that our API is complete we will use it to create our web application. The web app allows users to manage contacts from the browser.

Create a public folder in your project’s root directory and copy over the files from the example app’s public folder. The folder includes HTML templates and our AngularJS code.

As you look through the HTML files, you might notice that there’s some unconventional HTML code, such as “ng-view” in the index.html file:

<div class="container" ng-view>

These extensions are features of AngularJS’s template system. Templates allow us to reuse code and dynamically generate views for the end user.

Build the Web App with AngularJS

We’ll use AngularJS to tie everything together. AngularJS will help us to route user requests, render different views, and send data to and from the database.

Our AngularJS code resides in the /public/js folder in the app.js file. To simplify things, we’ll focus solely on the code that is required to retrieve and display contacts when the default homepage route (/) is requested. Implementing this functionality requires that we:

Render the appropriate view and template using the AngularJS routeProvider (index.html and list.html).

Fetch the contacts from the database using an AngularJS service (GET /contacts).

Pass the data from the service to the view with an AngularJS controller (ListController).

Our service functions leverage the built-in AngularJS $http service to generate HTTP requests. The module also returns a promise, which you can modify to add additional functionality (such as logging).

Note that with the $http service we use relative URL paths (for example, /contacts) as opposed to absolute paths like app-name.herokuapp.com/contacts.

Our controller adds the contacts data from our service to the homepage scope as a variable named contacts. This allows us to access the data directly from the template (list.html). We can iterate over the contacts data with AngularJS’s built-in ngRepeat directive:

Completing the Project

Now that we have an understanding of how we implemented the homepage route in AngularJS, the implementation for the rest of the web app routes can be found in the source project’s /public/js/app.js file. They all require a route definition in the routeProvider, one or more service functions to make the appropriate HTTP requests, and a controller to augment the scope.

Now that the web application component is complete, you can view your app by opening the website from the CLI:

$ heroku open

Summary

In this tutorial, you learned how to:

create a RESTful API server in Express and Node.js.

connect a MongoDB database to the API server for querying and persisting data.

create a rich web app using AngularJS.

We hope that you have seen the power of the MEAN stack to enable the development of common components for today’s web applications.

Notes on Scaling

If you are running a production MEAN application on Heroku, you will need to scale both your application and database as your traffic increases and data size grows. Refer to the Optimizing Node.js Application Concurrency article for best practices on scaling your application. To upgrade your database, see the mLab add-on documentation.

Optional next Steps

As we mentioned previously, this app intentionally omits details you would want to include in a real production application. In particular, we do not implement a user model, user authentication, or robust input validation. Consider adding these features as an additional exercise. If you have any questions about this tutorial, please let us know in the comments below.