pip
package manager to install necessary libraries.python -m venv fastapi_mongo_env
source fastapi_mongo_env/bin/activate # For Linux/Mac
fastapi_mongo_env\Scripts\activate # For Windows
fastapi
, uvicorn
(a server for running FastAPI applications), and pymongo
(the official MongoDB driver for Python).pip install fastapi uvicorn pymongo
from fastapi import FastAPI
from pymongo import MongoClient
app = FastAPI()
# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client["test_database"]
collection = db["test_collection"]
In the above code, we first import FastAPI
and MongoClient
. Then we create a FastAPI application instance. After that, we connect to the local MongoDB server running on the default port 27017
. We select a database named test_database
and a collection named test_collection
.
We can use Pydantic
models to define the structure of the data that our API will handle.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
Here, we define a Item
model with three fields: name
(a string), price
(a float), and is_offer
(a boolean which is optional).
Create an Item:
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
result = collection.insert_one(item_dict)
return {"id": str(result.inserted_id)}
In this endpoint, we receive an Item
object in the request body. We convert it to a dictionary and insert it into the MongoDB collection. We then return the ID of the inserted document.
Get an Item by ID:
@app.get("/items/{item_id}")
async def read_item(item_id: str):
item = collection.find_one({"_id": ObjectId(item_id)})
if item:
item["_id"] = str(item["_id"])
return item
return {"message": "Item not found"}
Here, we receive an item_id
as a path parameter. We try to find the item in the MongoDB collection using the ID. If found, we convert the _id
(which is a ObjectId
type in MongoDB) to a string and return the item. Otherwise, we return a “Item not found” message.
Note: You need to import ObjectId
from bson.objectid
at the top of your file:
from bson.objectid import ObjectId
Run the FastAPI Application:
uvicorn main:app --reload
Here, main
is the name of your Python file (assuming your code is in a file named main.py
) and app
is the name of your FastAPI application instance. The --reload
flag enables auto - reloading so that you don’t have to restart the server every time you make changes to your code.
Use a Tool like Postman or cURL:
curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name": "test_item", "price": 9.99, "is_offer": false}'
curl -X GET "http://127.0.0.1:8000/items/your_item_id"
try:
result = collection.insert_one(item_dict)
except Exception as e:
return {"error": str(e)}
Pydantic
models for input validation. It ensures that the data received by the API is in the correct format.collection.create_index("name")
pymongo
already has connection pooling built - in, but make sure to manage your connections properly to avoid resource exhaustion.Integrating FastAPI with MongoDB can provide a high - performance and scalable backend solution for your applications. By following the steps in this guide, you can set up a basic API that interacts with a MongoDB database. You can further expand this setup by adding more endpoints, improving error handling, and implementing security features.