HTTP Access to MongoDB Database With Data API
Recently MongoDB Atlas has launched Data API that enable developer to perform CRUD operations over HTTP, this service allow us to serve data to frontend directly from MongoDB database without any additional drivers or libraries needed. The use of Atlas Data API could significantly improve developer productivity as well as user experience, why so? let’s take an example of e-commerce website.
One of the most important feature in e-commerce website is shopping cart, customer uses it very often and sometimes left it as it is for a quite long time before proceed to checkout. While cart is essential, it’s store temporary data and must be available anywhere for every customer, so if an item was added to cart from web/desktop today it should still be there on app/mobile three days later (some e-commerce website store it for 30 days max). According to this requirement, we need backend to store and retrieve data from database.
By storing shopping cart data directly into NoSQL database backend developers can focus on another important features and frontend developers can release shopping cart feature independently since they no longer needed save-to-cart endpoint. Frequent request for add-update-delete item in shopping cart will not burden backend server but routed to NoSQL database cluster instead.
Enable Data API
By the time I wrote this MongoDB Data API is still in preview mode so to use it we need to enable Data API because it’s disabled by default, once you logged in into Atlas console click Data API in the left navigation menu, on the next screen select one or more available clusters then click Enable the Data API button.
Create Data API Key
API key used to manage access and prevent unauthorized request to Data API endpoint, hence any request must include a valid API key. Click button Create API Key and enter a unique name for your key then click Generate API Key. Don’t forget to copy and save your API key somewhere else because you won’t be able to see it again once the popup closed.
Please note that we should not embed API key directly in our client application to prevent security breaches, we can use either API gateway or function compute to route request to Data API and append api-key into request header.
Make a Test Request
Now we are all set, to test your API click on Test Your API button then select Cluster, Database and Collection you want. You can directly copy the cURL code snippet to terminal and run it, remember to replace <API_KEY> placeholder with you actual API Key.