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.
- Python 3.9.0
#Running the Example
To begin, you should clone the example code from GitHub.
1 git clone email@example.com:mongodb-developer/mongodb-with-fastapi.git
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.
1 cd mongodb-with-fastapi 2 pip install -r requirements.txt
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.
1 export MONGODB_URL="mongodb+srv://<username>:<password>@<url>/<db>?retryWrites=true&w=majority"
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.
1 uvicorn app:app --reload
Once the application has started, you can view it in your browser at http://127.0.0.1:8000/docs.
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.
1 client = motor.motor_asyncio.AsyncIOMotorClient(os.environ["MONGODB_URL"]) 2 db = client.college
We're using the async motor driver to create our MongoDB client, and then we specify our database name
#The _id Attribute and ObjectIds
1 class PyObjectId(ObjectId): 2 3 def __get_validators__(cls): 4 yield cls.validate 5 6 7 def validate(cls, v): 8 if not ObjectId.is_valid(v): 9 raise ValueError("Invalid objectid") 10 return ObjectId(v) 11 12 13 def __modify_schema__(cls, field_schema): 14 field_schema.update(type="string")
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