Python
MongoDB Developer Center
chevron-right
Developer Topics
chevron-right
Languages
chevron-right
Python
chevron-right

Getting Started with MongoDB and FastAPI

Aaron BassettPublished Feb 05, 2022 • Updated May 12, 2022
DjangoFastApiMongoDBPython
facebook icontwitter iconlinkedin icon
random alt
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.
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 two models, the StudentModel and the UpdateStudentModel.
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 allow_population_by_field_name to True in the model's Config class.
We set this id value automatically to an ObjectId string, 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 should never change.
  • All fields are optional, so you only need to supply the fields you wish to update.
Application Routes
Our application has five routes:
  • POST / - creates a new student.
  • GET / - view a list of all students.
  • GET /{id} - view a single student.
  • PUT /{id} - update a student.
  • DELETE /{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. 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
, a recent addition to Python (introduced in version 3.8) and often referred to by the incredibly 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
update_one
to
$set
the new values, and then return the updated document.
But 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.

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 the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Copy Link
facebook icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Code Example
GroupUs

May 24, 2022
Quickstart
Basic MongoDB Operations in Python

May 12, 2022
Article
Streaming Data with Apache Spark and MongoDB

May 19, 2022
Tutorial
Upgrade Fearlessly with the MongoDB Stable API

May 16, 2022
Table of Contents
  • Prerequisites