MongoDB
Using MongoDB as the database in FastAPI involves setting up the MongoDB client, defining MongoDB models, and integrating MongoDB operations into your FastAPI application. MongoDB is a NoSQL database, which means it stores data in JSON-like documents, making it flexible and scalable for various types of applications. Here’s a step-by-step guide to using MongoDB with FastAPI:
Step-by-Step Guide to Using MongoDB with FastAPI
1. Install Required Packages
You will need fastapi
for the web framework, pymongo
for MongoDB integration, and optionally pydantic
for data validation.
pip install fastapi pymongo
2. Set Up the Project Structure
Create a project structure as follows:
fastapi_mongodb/
│
├── main.py
├── database.py
├── models.py
├── schemas.py
└── requirements.txt
main.py
: FastAPI application setup.database.py
: MongoDB client initialization and connection setup.models.py
: MongoDB document models.schemas.py
: Pydantic models for data validation.
3. MongoDB Configuration and Connection
Set up database.py
to handle the MongoDB client initialization and connection.
# database.py
from pymongo import MongoClient
class MongoDB:
def __init__(self, connection_string: str, db_name: str):
self.client = MongoClient(connection_string)
self.db = self.client[db_name]
# Replace these with your MongoDB connection string and database name
MONGO_CONNECTION_STRING = "mongodb://localhost:27017/"
MONGO_DB_NAME = "fastapi_db"
mongo = MongoDB(connection_string=MONGO_CONNECTION_STRING, db_name=MONGO_DB_NAME)
- Replace
mongodb://localhost:27017/
with your MongoDB connection string. - Replace
fastapi_db
with your preferred database name.
4. Define MongoDB Models
Create models.py
to define your MongoDB document models using Pydantic schemas.
# models.py
from pydantic import BaseModel, Field
from bson import ObjectId
class User(BaseModel):
id: ObjectId = Field(default_factory=ObjectId, alias="_id")
username: str
email: str
full_name: str
hashed_password: str
is_active: bool
class Config:
allow_population_by_field_name = True
schema_extra = {
"example": {
"username": "johndoe",
"email": "johndoe@example.com",
"full_name": "John Doe",
"hashed_password": "hashed_password_here",
"is_active": True,
}
}
- Use
bson.ObjectId
for the_id
field, which MongoDB uses for unique identifiers. - Adjust the fields according to your application's requirements.
5. Pydantic Schemas for Data Validation
Create schemas.py
to define Pydantic schemas for data validation and serialization.
# schemas.py
from pydantic import BaseModel
class UserBase(BaseModel):
username: str
email: str
full_name: str | None = None
is_active: bool | None = None
class UserCreate(UserBase):
password: str
class User(UserBase):
id: str
class Config:
orm_mode = True
UserBase
: Base schema for common user fields.UserCreate
: Schema for user creation, including the password.User
: Schema for representing a user, including the ID.
6. CRUD Operations with MongoDB
Implement CRUD operations in database.py
or create a new file (crud.py
) for these operations.
# database.py or crud.py
from .models import User
from .mongo import mongo
def create_user(user_data: dict):
return mongo.db.users.insert_one(user_data)
def get_users():
return list(mongo.db.users.find())
def get_user(user_id: str):
return mongo.db.users.find_one({"_id": ObjectId(user_id)})
def update_user(user_id: str, user_data: dict):
return mongo.db.users.update_one({"_id": ObjectId(user_id)}, {"$set": user_data})
def delete_user(user_id: str):
return mongo.db.users.delete_one({"_id": ObjectId(user_id)})
- Use
mongo.db.users
to access theusers
collection in MongoDB. - Implement functions for creating, reading, updating, and deleting users.
7. Create FastAPI Endpoints
Implement FastAPI endpoints in main.py
to interact with MongoDB using the defined CRUD operations.
# main.py
from fastapi import FastAPI, HTTPException, Depends
from . import schemas, database
app = FastAPI()
@app.post("/users/", response_model=schemas.User)
async def create_user(user: schemas.UserCreate):
user_dict = user.dict()
user_dict["hashed_password"] = "fakehashed" # Replace with real hashing
del user_dict["password"]
result = database.create_user(user_dict)
user.id = result.inserted_id
return user
@app.get("/users/", response_model=list[schemas.User])
async def read_users():
return database.get_users()
@app.get("/users/{user_id}", response_model=schemas.User)
async def read_user(user_id: str):
user = database.get_user(user_id)
if user:
return user
raise HTTPException(status_code=404, detail="User not found")
@app.put("/users/{user_id}", response_model=schemas.User)
async def update_user(user_id: str, user: schemas.UserBase):
updated_user = database.update_user(user_id, user.dict(exclude_unset=True))
if updated_user:
return updated_user
raise HTTPException(status_code=404, detail="User not found")
@app.delete("/users/{user_id}", response_model=dict)
async def delete_user(user_id: str):
deleted_user = database.delete_user(user_id)
if deleted_user.deleted_count:
return {"message": "User deleted successfully"}
raise HTTPException(status_code=404, detail="User not found")
- Implement endpoints for creating, reading, updating, and deleting users.
- Use
schemas.User
,schemas.UserCreate
, and other schemas for request and response validation.
8. Running the Application
Start your FastAPI application using Uvicorn:
uvicorn main:app --reload
- Open your browser and navigate to
http://localhost:8000/docs
to access the interactive Swagger UI. - Use the endpoints to interact with your MongoDB database.
Conclusion
This guide provides a foundation for integrating MongoDB with FastAPI to build scalable and efficient API services. By following these steps, you can leverage MongoDB's flexibility and FastAPI's performance to develop modern web applications.
Further Reading
- FastAPI Documentation: FastAPI Official Documentation
- MongoDB Documentation: MongoDB Official Documentation
- Pydantic Documentation: Pydantic Official Documentation
- Uvicorn Documentation: Uvicorn Official Documentation
These resources will help you further explore and expand your knowledge of building APIs with FastAPI and MongoDB.