Create a quick mongoDB API in 4 lines of code

Siso ngqolosi
3 min readOct 4, 2022

--

Scenario: You have data in a spreadsheet, json file or the data is already in your mongoDB collection.

I will quickly show you how to create an API with mongoDB. I assume you already have a mongoDB account and you are familiar with the mongoDB interface.

The API we are going to create is for a simple online store, see snapshot below.

If you already have data in your mongoDB database you can skip to the section below.

Current I have the data in an google sheets file:

https://docs.google.com/spreadsheets/d/1at7RVT06W9OdCTJz9vEc4xqUCq0jztj9ixwZc7GqHQI/edit?usp=sharing

Save the data as a CSV or json so we can import it to mongoDB. If you have to do some transformations to your json file you can use https://www.convertsimple.com/convert-javascript-to-json/ or https://codebeautify.org/jsonviewer

I have the mongoDB Compass installed because it allows you import csv or json files install of adding all the entries manually. So I created a new database called onlineshop and a collection named onlineshop.

Your compass will look something like the file below:

Simply import the CSV file or JSON file. Ensure the Fields and Types match

Now it’s time to create the API:

  1. Go to the mongoDB website and log in. Go to the collection and database you created. Go to the App Services tap at the top next to Altas.

2. Click on create a New App.

3. Give it a name (“onlineshop”) in my case and click on the use an existing MongoDB Source. Create the new service.

4. Click on the HTTPS Endpoints (Bottom left).

5. Click on Add endpoint

6. Endpoint route /onlineshop“Endpoint route must not be empty.” Copy the callback URL. We are going to use it when fetching.

7. Ensure the Respond With Results is checked.

8. Add a new function. I named it postProductFunction.

9. Delete the sample code and copy then paste the following:

Change the dbname and collection_name to reflect your own.

10. We are not going to request validation for this example.

11. Save the Draft then review & deploy.

12. Click on the Functions Tab and then in settings next to the Function Editor. Under Authentication select System since we are not going to authenticate users. Save the Draft then review & deploy.

13. Go to postman and paste the Callback URL. Change the method to POST and then press end. you should get all the products.

Success !!! If you are getting problems. Let me know in the comments section.

Photo by Austin Park on Unsplash

--

--