Use REST API to Connect with Mongo with PHP
After getting your basic understanding of mLab (formerly MongoLabs) from our previous tutorial, we now show you how to connect to the Mongo database on mLab.com using PHP and the REST APIs provided by mLab (as documented here).
As mentioned in the docs, using REST APIs to interact with Mongo is not the preferred method. It is recommended you use Mongo DB drivers instead (there is one for PHP). However, some people may be on web hosts where they can not install Mongo drivers and not have this available. In that case, as a last resort we use REST APIs, which is less performant and less secure.
Protect your API Key
The one important thing to keep in mind when using REST APIs is to protect your API key. Someone who can see your API key can access and do whatever they want with all databases in your account. Do not place API keys in public source depositories. Do not put key in front-end code.
In these tutorials, I have API keys inside the PHP files (which can not be publicly seen as long as the PHP interpreter on the server does not go down). While I’m only doing this to keep tutorials simple, you should not do this in real production environments. Rather hide the key out in either server environment variables, or in config files outside of document root, or other more secure techniques.
Enable REST and get API Key
You first have to enable REST API in your mLab. This is done by clicking on your “username” (not “account name”) in mLab dashboard and get to this screen …
The only reason I am showing you my API key in the screenshots is that I will click the “Regenerate API key” to get a new key before publishing these tutorials. Also I will “Disable Data API access” afterwards.
New Mongo DB and User
I have created a new database “employee-list” with a collection called “employees” which currently has no documents…
I’ve also added an user to the database. Although we won’t be using its username nor password in the following code, all databases need to have at least one user.
Adding Document using REST API
Now I will add a new document to this collection using the REST API. According to the doc (which is written for jQuery), it works like this …
We have to translate this to PHP. First we need to construct the URL by replacing the above with our specific database name and collection name and of course our own API key. In our case, we have…
Because the REST endpoint URLs contain the API key, these calls are meant to be used only in server-side code, not from front-end Javascript code where the code is visible.
Next, we want to add a new document containing the name of an employee and his “status” (of whether ‘busy’ or ‘available’)…
Following the model in PHP docs for stream_context_create, we create a stream context to pass into file_get_contents …
Note the Content-type is ‘application/json’.
If we run this code, we get a $returnVal that looks like this …
Mongo has automatically added an “object id” for this newly added document, which you can also see in the Mongo dashboard…
Retrieving Documents using REST API
Since we now have a document in our collection, let’s see how we can use REST API to simply list the employees in our “employees” collection. The endpoint URL is same, but this time we use a simply “GET” with file_get_contents instead of a post. If you simply paste the URL into the browser, you will get the results in JSON form. However, in PHP we decode the JSON into an PHP object …
When we print out this $employees object, you see the document with the id…
We can grab the fields in the object like this …
However, to get also the object id requires a bit of work, because PHP is getting confused with the dollar sign in front of “$oid”. The work-around is like this by iterating through each field of “$employee->_id” and then displaying the “$oid” field…
Replacing values using REST API
We need the $oid of a particular document if we are to replace John’s “status” from “busy” to “available” while keeping all other fields untouched. The URL has changed because it now contains the document id after the collection. This time we use the “PUT” method…
In the $newStatus, we use the “$set” syntax, because if we did this instead …
It would have replaced the whole document, losing the name field.
Using Query Parameters
Using the “q” parameter in the query string, we can list all employees that have status available …
Or get the result count by adding the c=true query parameter…
and others as listed in the docs.
Deleting using REST API
Finally, let’s delete document 57e8932fbd966f6e940f01f8 …
That’s it. Now you know how to Create, Read, Update, and Delete (also known as CRUD) using REST APIs for mLab.