0
0
FastapiHow-ToBeginner · 3 min read

How to Connect to MongoDB with FastAPI: Simple Guide

To connect FastAPI to MongoDB, use the Motor library, which supports async operations. Create a MotorClient instance, connect to your database, and use it inside your FastAPI routes for efficient async database access.
📐

Syntax

Here is the basic syntax to connect FastAPI with MongoDB using Motor:

  • MotorClient: Creates an async client to MongoDB.
  • db = client.database_name: Selects the database.
  • Use async functions in FastAPI routes to query MongoDB.
python
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI

app = FastAPI()

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.your_database_name

@app.get("/")
async def read_data():
    document = await db.your_collection.find_one({})
    if document:
        document["_id"] = str(document["_id"])
    return document
💻

Example

This example shows a complete FastAPI app connecting to MongoDB, inserting a document, and fetching it asynchronously.

python
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.testdb

class Item(BaseModel):
    name: str
    description: str

@app.post("/items/")
async def create_item(item: Item):
    result = await db.items.insert_one(item.dict())
    return {"inserted_id": str(result.inserted_id)}

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    from bson import ObjectId
    document = await db.items.find_one({"_id": ObjectId(item_id)})
    if document:
        document["_id"] = str(document["_id"])
    return document
Output
POST /items/ with JSON {"name":"Pen","description":"Blue ink"} returns {"inserted_id":"<some_object_id>"} GET /items/<some_object_id> returns {"_id":"<some_object_id>","name":"Pen","description":"Blue ink"}
⚠️

Common Pitfalls

Common mistakes when connecting FastAPI to MongoDB include:

  • Using synchronous MongoDB drivers instead of async ones like Motor, which blocks FastAPI's async event loop.
  • Not awaiting async database calls, causing errors or unexpected behavior.
  • Forgetting to convert MongoDB ObjectId to string before returning JSON responses.
python
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI

app = FastAPI()

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.testdb

@app.get("/wrong")
def wrong_read():
    # This is wrong because it's not async and does not await
    document = db.items.find_one({})
    return document

@app.get("/right")
async def right_read():
    document = await db.items.find_one({})
    if document:
        document["_id"] = str(document["_id"])
    return document
📊

Quick Reference

Tips for connecting FastAPI to MongoDB:

  • Use motor.motor_asyncio.AsyncIOMotorClient for async MongoDB access.
  • Always use await with Motor calls inside async FastAPI routes.
  • Convert ObjectId to string before returning JSON.
  • Keep MongoDB connection client global to reuse connections efficiently.

Key Takeaways

Use Motor library for async MongoDB connection in FastAPI.
Always await database calls inside async route functions.
Convert MongoDB ObjectId to string before sending JSON responses.
Create a global MongoDB client to reuse connections efficiently.
Avoid synchronous MongoDB drivers to prevent blocking FastAPI.