Build an API to MongoDB -- fast

AnyPresence JustAPIs helps you create and deploy REST APIs on your database in minutes; simply follow these steps

By building a REST API, developers can create a foundation upon which either internal teams or a broader ecosystem can incorporate content or functionality into modern applications. Because most apps will need to persist data in some sort of database store, building APIs that expose CRUD (create, read, update, delete) functions on popular databases is often a critical requirement.

Common database choices include open source solutions such as MySQL, PostgreSQL, and MongoDB. With AnyPresence JustAPIs, developers can easily build and deploy APIs on top of these databases, wherever they happen to be hosted, be it in the cloud or on premises.

MongoDB is a popular document-oriented NoSQL database that stores data in JSON-like format and allows developers to perform SQL-like queries against it. In this article, we will walk through a brief tutorial to illustrate how easy it is to build and deploy an API on top of your MongoDB instance. 

Let’s get started

Before you start, sign up for JustAPIs. Once you have confirmed your registration through the link provided in the confirmation email, sign in and download the Samples.json found in Step 4 of the Quick Start Guide.

justapis 1 home

The only other requirement is that JustAPIs must be able to access your MongoDB instance. Our tutorial will draw on a cloud-based MongoDB instance hosted by mLab (formerly MongoLab). (You can sign up for a free account at mLab or to get a hosted MongoDB instance of your own.) If you have MongoDB running locally, you can download the JustAPIs server from the welcome email and follow the same instructions.

In this example we will create a proxy endpoint that uses the JustAPIs single call component to update the name attribute in a MongoDB collection called hats. You can replace name and hats with any attribute and collection within your own MongoDB instance.

Step 1. From the JustAPIs home screen, click the Build button, enter a name for your new API, and import the Samples.json file:

justapis 2 import

Click Save, and you’ll find your API listed with its URL:

justapis 3 myapi

Step 2. Click on your new API and select the Remote Endpoints box at the left of the dashboard. Scroll down to find the MongoLab remote endpoint in the list of remote endpoints and click into it. 

justapis 4 remote endpoints

Step 3. When you are in edit mode, you will see that this remote endpoint has many fields available to specify all of the credentials of your MongoDB. Enter the credentials for your MongoDB where the fields say “Change Me” and hit Save:

justapis 5 mlab

In your MongoDB, create a hats collection with one document that has the key name, where name has the value Fadidas:

justapis 6 hats fadidas

Now that we have set up our external data source, let’s create our actual proxy endpoint.

Step 4. Find the MongoUpdate proxy, which should appear in the list of proxy endpoints, and click the edit icon that appears when you hover over the row:

justapis 7 proxy endpoints

Step 5. When you are in edit mode, you will see that this proxy endpoint has several properties that were specified when it was created:

justapis 8 mongoupdate

There are a number of points to note here:

  1. The proxy endpoint’s name is MongoUpdate, which is used for display purposes in the admin web app.
  2. The Active status is set to on, which means this proxy endpoint will run if the server receives a request for it.
  3. This proxy endpoint is assigned to the Dev environment, and any environment variables used will be populated from the Dev environment.
  4. This proxy endpoint is assigned to the Mongo group.
  5. There is one route defined, which is a Put method at /employee/{id}. This means that if the host is http://localhost:5000, the full URL for this proxy endpoint will be http://localhost:5000/employee/{id}. Request parameters can be exposed to logic components via interpolated strings, in this case id.

Step 6. Note there is one step in this proxy endpoint workflow that is a single call component. Click on the single call component icon to view the details of the first step in the workflow:

justapis 9 single call

You will see that this single call component is composed of several substeps. First, the Conditional option is set to If, which means that any JavaScript logic specified in the conditional logic block must evaluate to true to continue. Otherwise, the workflow will skip to the end. Second, there is no conditional logic specified, so the workflow will move to the next substep. Third, note that the before request logic block has several lines of JavaScript. The first line is:

var id = ;

This first line stores the request parameter that was exposed earlier in the route via {id} into a variable named id. Note that this type of parameter is exposed via the request.vars object. 

The second line instantiates a new Mongo-type request:

mongo.request = new AP.Mongo.Request();

This line creates a new instance of an AnyPresence Mongo request, allowing the user to query the remote endpoint’s MongoDB.

The third line is:

var nameUpdate  =  JSON.parse(request.body).name ;

This line accomplishes several things at once. Note that the same request object we used earlier to grab the {id} also exposes the body data sent in the request, accessed this time with request.body. We only want to update the name attribute in this proxy endpoint, so we must first use JavaScript’s JSON.parse() method to convert our request.body into a usable JSON object. By accessing only name, we can now store the newly requested name in nameUpdate

The last line specifies the actual Mongo request:

mongo.request.query('hats',  'update' ,   {"__id":{"__id":id , "type":"id"}} , {"name": nameUpdate});

Using the query method, we specify in order as you see above, the collection (hats), operation type (update), the record (via id), and the attribute we want to update (name). Note the hash value of id; this is letting the AnyPresence Mongo method know that this ID is a Mongo hex-formatted ID. 

Now we need to point the remote endpoint to MongoLab, which we set up in Steps 1 and 2. Each single call component requires a remote endpoint in order to know the data source being used in the component.

The final step in the single call component is the logic block located after the request. This block is typically used to form the response of the proxy endpoint including logic to define cases for different HTTP status codes. Our sample contains two lines in the after request logic block.

justapis 10 after request

The first line is:

response.statusCode = 200

This line sets the status code to a 200 to indicate a successful call. Just as the request object is called request, the response object is exposed as response

The second line sets the response body:

response.body = JSON.stringify(;

Here we use JavaScript’s JSON.stringify method, which converts a JavaScript value into a valid JSON string. Notice that the mongo object from the before request logic block is used here to access the response from the Mongo query. MongoDB does not return the updated document as the response to an update query, so the expected outcome of the body should be null. 

Step 7. Now let us test this proxy endpoint. Click on the initial proxy endpoint bubble and create a test route with a hard-coded id of whatever your Mongo document’s ID is, in this case 574f97ae8736449341751714:

justapis 11 testroute

Click on the test-tube icon to create a new test that can run this route:

justapis 12 test

Set the method as PUT and create a request body that sets name to Nikie, for example. Save the test and hit Execute.

justapis 13 test response

As expected, you get a 200 result and a null body. Check your MongoDB to see the update:

justapis 14 confirm update

(Note: You can get a more informative response from your update call by returning the record itself by chaining another single call component after the update component you just completed, with another Mongo query using the operator find.)

Congratulations, you have built and deployed an API on your MongoDB instance!

Now that you know how to API-enable popular databases, you can become a microservices expert and enable rapid app development within your organization. Try out the other JustAPIs tutorials available and let the world know about the awesome APIs you've built.

Richard Mendis is co-founder of AnyPresence.

New Tech Forum provides a venue to explore and discuss emerging enterprise technology in unprecedented depth and breadth. The selection is subjective, based on our pick of the technologies we believe to be important and of greatest interest to InfoWorld readers. InfoWorld does not accept marketing collateral for publication and reserves the right to edit all contributed content. Send all inquiries to

From CIO: 8 Free Online Courses to Grow Your Tech Skills
View Comments
Join the discussion
Be the first to comment on this article. Our Commenting Policies