EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Python
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Pythonchevron-right

Getting Started with MongoDB and FastAPI

Aaron Bassett, Mark Smith7 min read • Published Feb 05, 2022 • Updated Mar 11, 2024
DjangoFastApiMongoDBPython
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
QuickStart Python Logo
FastAPI is a modern, high-performance, easy-to-learn, fast-to-code, production-ready, Python 3.6+ framework for building APIs based on standard Python type hints. While it might not be as established as some other Python frameworks such as Django, it is already in production at companies such as Uber, Netflix, and Microsoft.
FastAPI is async, and as its name implies, it is super fast; so, MongoDB is the perfect accompaniment. In this quick start, we will create a CRUD (Create, Read, Update, Delete) app showing how you can integrate MongoDB with your FastAPI projects.

Prerequisites

  • Python 3.9.0
  • A MongoDB Atlas cluster. Follow the "Get Started with Atlas" guide to create your account and MongoDB cluster. Keep a note of your username, password, and connection string as you will need those later.

Running the Example

You will need to install a few dependencies: FastAPI, Motor, etc. I always recommend that you install all Python dependencies in a virtualenv for the project. Before running pip, ensure your virtualenv is active.
It may take a few moments to download and install your dependencies. This is normal, especially if you have not installed a particular package before.
Once you have installed the dependencies, you need to create an environment variable for your MongoDB connection string.
Remember, anytime you start a new terminal session, you will need to set this environment variable again. I use direnv to make this process easier.
The final step is to start your FastAPI server.
Screenshot of terminal running FastAPI
Once the application has started, you can view it in your browser at http://127.0.0.1:8000/docs.
Screenshot of browser and swagger UI
Once you have had a chance to try the example, come back and we will walk through the code.

Creating the Application

All the code for the example application is within app.py. I'll break it down into sections and walk through what each is doing.

Connecting to MongoDB

One of the very first things we do is connect to our MongoDB database.
We're using the async motor driver to create our MongoDB client, and then we specify our database name college.

The _id Attribute and ObjectIds

MongoDB stores data as BSON. FastAPI encodes and decodes data as JSON strings. BSON has support for additional non-JSON-native data types, including ObjectId which can't be directly encoded as JSON. Because of this, we convert ObjectIds to strings before storing them as the id field.

Database Models

Many people think of MongoDB as being schema-less, which is wrong. MongoDB has a flexible schema. That is to say that collections do not enforce document structure by default, so you have the flexibility to make whatever data-modelling choices best match your application and its performance requirements. So, it's not unusual to create models when working with a MongoDB database. Our application has three models, the StudentModel, the UpdateStudentModel, and the StudentCollection.
This is the primary model we use as the response model for the majority of our endpoints.
I want to draw attention to the id field on this model. MongoDB uses _id, but in Python, underscores at the start of attributes have special meaning. If you have an attribute on your model that starts with an underscore, pydantic—the data validation framework used by FastAPI—will assume that it is a private variable, meaning you will not be able to assign it a value! To get around this, we name the field id but give it an alias of _id. You also need to set populate_by_name to True in the model's model_config
We set this id value automatically to None, so you do not need to supply it when creating a new student.
The UpdateStudentModel has two key differences from the StudentModel:
  • It does not have an id attribute as this cannot be modified.
  • All fields are optional, so you only need to supply the fields you wish to update.
Finally, StudentCollection is defined to encapsulate a list of StudentModel instances. In theory, the endpoint could return a top-level list of StudentModels, but there are some vulnerabilities associated with returning JSON responses with top-level lists.

Application Routes

Our application has five routes:
  • POST /students/ - creates a new student.
  • GET /students/ - view a list of all students.
  • GET /students/{id} - view a single student.
  • PUT /students/{id} - update a student.
  • DELETE /students/{id} - delete a student.

Create Student Route

The create_student route receives the new student data as a JSON string in a POST request. We have to decode this JSON request body into a Python dictionary before passing it to our MongoDB client.
The insert_one method response includes the _id of the newly created student (provided as id because this endpoint specifies response_model_by_alias=False in the post decorator call. After we insert the student into our collection, we use the inserted_id to find the correct document and return this in our JSONResponse.
FastAPI returns an HTTP 200 status code by default; but in this instance, a 201 created is more appropriate.
Read Routes
The application has two read routes: one for viewing all students and the other for viewing an individual student.
Motor's to_list method requires a max document count argument. For this example, I have hardcoded it to 1000; but in a real application, you would use the skip and limit parameters in find to paginate your results.
The student detail route has a path parameter of id, which FastAPI passes as an argument to the show_student function. We use the id to attempt to find the corresponding student in the database. The conditional in this section is using an assignment expression, an addition to Python 3.8 and often referred to by the cute sobriquet "walrus operator."
If a document with the specified _id does not exist, we raise an HTTPException with a status of 404.
Update Route
The update_student route is like a combination of the create_student and the show_student routes. It receives the id of the document to update as well as the new data in the JSON body. We don't want to update any fields with empty values; so, first of all, we iterate over all the items in the received dictionary and only add the items that have a value to our new document.
If, after we remove the empty values, there are no fields left to update, we instead look for an existing record that matches the id and return that unaltered. However, if there are values to update, we use find_one_and_update to $set the new values, and then return the updated document.
If we get to the end of the function and we have not been able to find a matching document to update or return, then we raise a 404 error again.
Delete Route
Our final route is delete_student. Again, because this is acting upon a single document, we have to supply an id in the URL. If we find a matching document and successfully delete it, then we return an HTTP status of 204 or "No Content." In this case, we do not return a document as we've already deleted it! However, if we cannot find a student with the specified id, then instead we return a 404.

Our New FastAPI App Generator

If you're excited to build something more production-ready with FastAPI, React & MongoDB, head over to the Github repository for our new FastAPI app generator and start transforming your web development experience.

Wrapping Up

I hope you have found this introduction to FastAPI with MongoDB useful. If you would like to learn more, check out my post introducing the FARM stack (FastAPI, React and MongoDB) as well as the FastAPI documentation and this awesome list.
If you have questions, please head to our developer community website where MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Learn to Build AI-Enhanced Retail Search Solutions with MongoDB and Databricks


Sep 25, 2023 | 14 min read
Tutorial

Scaling for Demand: Deploying Python Applications Using MongoDB Atlas on Azure App Service


May 01, 2023 | 12 min read
Tutorial

How to Implement Databricks Workflows and Atlas Vector Search for Enhanced Ecommerce Search Accuracy


Sep 22, 2023 | 6 min read
Tutorial

Adding Authentication to Your FARM Stack App


Sep 23, 2022 | 7 min read
Table of Contents