BlogAtlas Vector Search voted most loved vector database in 2024 Retool State of AI reportLearn more >>
MongoDB Developer
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right

8 Best Practices for Building FastAPI and MongoDB Applications

Mark Smith8 min read • Published Apr 23, 2024 • Updated Apr 23, 2024
Facebook Icontwitter iconlinkedin icon
Rate this article
FastAPI is a modern, high-performance web framework for building APIs with Python 3.8 or later, based on type hints. Its design focuses on quick coding and error reduction, thanks to automatic data model validation and less boilerplate code. FastAPI’s support for asynchronous programming ensures APIs are efficient and scalable, while built-in documentation features like Swagger UI and ReDoc provide interactive API exploration tools.
FastAPI seamlessly integrates with MongoDB through the Motor library, enabling asynchronous database interactions. This combination supports scalable applications by enhancing both the speed and flexibility of data handling with MongoDB. FastAPI and MongoDB together are ideal for creating applications that manage potentially large amounts of complex and diverse data efficiently. MongoDB is a proud sponsor of the FastAPI project, so you can tell it's a great choice for building applications with MongoDB.
All the techniques described in this article are available on GitHub — check out the source code! With that out of the way, now we can begin…
FastAPI is particularly suitable for building RESTful APIs, where requests for data and updates to the database are made using HTTP requests, usually with JSON payloads. But the framework is equally excellent as a back end for HTML websites or even full single-page applications (SPAs) where the majority of requests are made via JavaScript. (We call this the FARM stack — FastAPI, React, MongoDB — but you can swap in any front-end component framework that you like.) It's particularly flexible with regard to both the database back-end and the template language used to render HTML.

Use the right driver!

There are actually two Python drivers for MongoDB — PyMongo and Motor — but only one of them is suitable for use with FastAPI. Because FastAPI is built on top of ASGI and asyncio, you need to use Motor, which is compatible with asyncio. PyMongo is only for synchronous applications. Fortunately, just like PyMongo, Motor is developed and fully supported by MongoDB, so you can rely on it in production, just like you would with PyMongo.
You can install it by running the following command in your terminal (I recommend configuring a Python virtual environment first!):
The srv extra includes some extra dependencies that are necessary for connecting with MongoDB Atlas connection strings.
Once installed, you'll need to use the AsyncIOMotorClient in the motor.motor_asyncio package.
Note that the connection string is not stored in the code! Which leads me to…

Keep your secrets safe

It's very easy to accidentally commit secret credentials in your code and push them to relatively insecure places like shared Git repositories. I recommend making it a habit to never put any secret in your code.
When working on code, I keep my secrets in a file called .envrc — the contents get loaded into environment variables by a tool called direnv. Other tools for keeping sensitive credentials out of your code include envdir, a library like python-dotenv, and there are various tools like Honcho and Foreman. You should use whichever tool makes the most sense to you. Whether the file that keeps your secrets is called .env or .envrc or something else, you should add that filename to your global gitignore file so that it never gets added to any repository.
In production, you should use a KMS (key management system) such as Vault, or perhaps the cloud-native KMS of whichever cloud you may be using to host your application. Some people even use a KMS to manage their secrets in development.

Initialize your database connection correctly

Although I initialized my database connection in the code above at the top level of a small FastAPI application, it's better practice to gracefully initialize and close your client connection by responding to startup and shutdown events in your FastAPI application. You should also attach your client to FastAPI's app object to make it available to your path operation functions wherever they are in your codebase. (Other frameworks sometimes refer to these as “routes” or “endpoints.” FastAPI calls them “path operations.”) If you rely on a global variable instead, you need to worry about importing it everywhere it's needed, which can be messy.
The snippet of code below shows how to respond to your application starting up and shutting down, and how to handle the client in response to each of these events:

Consider using a Pydantic ODM

An ODM, or object-document mapper, is a library that converts between documents and objects in your code. It's largely analogous to an ORM in the world of RDBMS databases. Using an ODM is a complex topic, and sometimes they can obscure important things, such as the way data is stored and updated in the database, or even some advanced MongoDB features that you may want to take advantage of. Whichever ODM you choose, you should vet it highly to make sure that it's going to do what you want and grow with you.
If you're choosing an ODM for your FastAPI application, definitely consider using a Pydantic-based ODM, such as ODMantic or Beanie. The reason you should prefer one of these libraries is that FastAPI is built with tight integration to Pydantic. This means that if your path operations return a Pydantic object, the schema will automatically be documented using OpenAPI (which used to be called Swagger), and FastAPI also provides nice API documentation under the path "/docs". As well as documenting your interface, it also provides validation of the data you're returning.
The profile object above is automatically documented at the "/docs" path:
A screenshot of the auto-generated documentation

You can use Motor directly

If you feel that working directly with the Python MongoDB driver, Motor, makes more sense to you, I can tell you that it works very well for many large, complex MongoDB applications in production. If you still want the benefits of automated API documentation, you can document your schema in your code so that it will be picked up by FastAPI.

Remember that some BSON has more types than JSON

As many FastAPI applications include endpoints that provide JSON data that is retrieved from MongoDB, it's important to remember that certain types you may store in your database, especially the ObjectID and Binary types, don't exist in JSON. FastAPI fortunately handles dates and datetimes for you, by encoding them as formatted strings.
There are a few different ways to handle ObjectID mappings. The first is to avoid them completely by using a JSON-compatible type (such as a string) for _id values. In many cases, this isn't practical though, because you already have data, or just because ObjectID is the most appropriate type for your primary key. In this case, you'll probably want to convert ObjectIDs to a string representation when converting to JSON, and do the reverse with data that's being submitted to your application.
If you're using Beanie, it automatically assumes that the type of your _id is an ObjectID, and so will set the field type to PydanticObjectId, which will automatically handle this serialization mapping for you. You won't even need to declare the id in your model!

Define Pydantic types for your path operation responses

If you specify the response type of your path operations, FastAPI will validate the responses you provide, and also filter any fields that aren't defined on the response type.
Because ODMantic and Beanie use Pydantic under the hood, you can return those objects directly. Here's an example using Beanie:
If you're using Motor, you can still get the benefits of documentation, conversion, validation, and filtering by returning document data, but by providing the Pydantic model to the decorator:

Remember to model your data appropriately

A common mistake people make when building RESTful API servers on top of MongoDB is to store the objects of their API interface in exactly the same way in their MongoDB database. This can work very well in simple cases, especially if the application is a relatively straightforward CRUD API.
In many cases, however, you'll want to think about how to best model your data for efficient updates and retrieval and aid in maintaining referential integrity and reasonably sized indexes. This is a topic all of its own, so definitely check out the series of design pattern articles on the MongoDB website, and maybe consider doing the free Advanced Schema Design Patterns online course at MongoDB University. (There are lots of amazing free courses on many different topics at MongoDB University.)
If you're working with a different data model in your database than that in your application, you will need to map values retrieved from the database and values provided via requests to your API path operations. Separating your physical model from your business model has the benefit of allowing you to change your database schema without necessarily changing your API schema (and vice versa).
Even if you're not mapping data returned from the database (yet), providing a Pydantic class as the response_model for your path operation will convert, validate, document, and filter the fields of the BSON data you're returning, so it provides lots of value! Here's an example of using this technique in a FastAPI app:

Use the Full-Stack FastAPI & MongoDB Generator

My amazing colleagues have built an app generator to do a lot of these things for you and help get you up and running as quickly as possible with a production-quality, dockerized FastAPI, React, and MongoDB service, backed by tests and continuous integration. You can check it out at the Full-Stack FastAPI MongoDB GitHub Repository.
The homepage of an app built with the FastAPI Generator


Hopefully, this article has provided you with the knowledge to build a FastAPI application that will scale in both the amount of code you write, and the data you need to store. We're always looking for more tricks and tips for building applications with FastAPI and MongoDB, so if you have some suggestions, why not open a ticket on GitHub and we can have a chat?

Let us know what you're building!

We love to know what you're building with FastAPI or any other framework — whether it's a hobby project or an enterprise application that's going to change the world. Let us know what you're building at the MongoDB Community Forums. It's also a great place to stop by if you're having problems — someone on the forums can probably help you out!
Top Comments in Forums
There are no comments on this article yet.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this article

Enable Generative AI and Semantic Search Capabilities on Your Database With MongoDB Atlas and OpenAI

Jun 25, 2024 | 8 min read

MongoDB Aggregation Pipeline Queries vs SQL Queries

May 10, 2022 | 7 min read

MongoDB & Mongoose: Compatibility and Comparison

Apr 02, 2024 | 11 min read

Create a Data Pipeline for MongoDB Change Stream Using Pub/Sub BigQuery Subscription

Apr 02, 2024 | 5 min read
Table of Contents