I have a personal project building a SaaS as a startup idea. For now, I am developing the building blocks to complete the whole infrastructure, from mobile app development, backup database design, business plan and etc.
For today, I want to build a API services backend that will take requests from mobile and web applications and perform transaction on the backend database, MongoDB in this case, but I will still considering between MongoDB and Firebase.
I am using Python, FastAPI, Pydantic and Pymongo to access the backend database, which is a free tier MongoDB on Atlas.
These are the entire code base. I will do through it in slightly more detail later.
Full disclosure, I copied the code from a great YouTube Video and you can find the github repository of his code in the video description too.

For main.py, the starting point of the program is very simple, just import some library and call FastAPI function.

To connect to the backend database, which is my personal free tier Mongo Atlas in Google Cloud, I used pymongo module to make the connection to the collection. I should also put the name of the database and the name of the collection in my .env file instead of hardcoding it in the code.

The data model is very simple, just to test out the functionality. Am using pydantic BaseModel to define the User class

To handle the data return from MongoDB backend, will need a way to translate the data to fit into the data model above. The youtube creator did a very cool thing to get the code flexible enough to handle any kind of return from the database without hardcoding the fields. Pretty smart. All the credit to him.

Now the meat of the code, handling the API call. Here include the code for API call for get all, get one document and insert one new document to the collection. I added the exception handling, still not perfect, but it capture some of the error.

Next are updating the document and also deleting the document.

To run the code in my local machine, just call uvicorn with the name of the entry code.

The beauty of FastAPI is that the framework come with swagger that can be use for testing the code. Pretty handy, one of the reason that I like fastAPI. To access to it, just point the browser to “http://127.0.0.1:8000/docs”

This is how to call get to retrieve all documents from the collection

All the codes were uploaded to my Github repository. Feel free to take a look, comments and suggestions are welcome.
Things that I need to work on is to get these on cloud run or cloud function. That will be another blog post, was testing cloud function using Secret Manager and local environment variables. Pretty Cool.
Onward. 1% better everyday!!!
