Building a RESTful API with FastAPI and MongoDB

Amar
3 min readJun 27, 2024

--

In today’s world of web development, building efficient and scalable APIs is In the contemporary landscape of web development, the creation of efficient and scalable APIs holds paramount importance. FastAPI, recognized for its modern architecture and rapid performance, is a prominent web framework tailored for API development in Python 3.7+ (with asynchronous support introduced in Python 3.8+). Concurrently, MongoDB stands out as a widely adopted NoSQL database celebrated for its versatility and scalability, rendering it an optimal solution for managing unstructured or semi-structured data

In this discussion, we will delve into the integration of FastAPI with MongoDB to construct a RESTful API. By the conclusion, you will gain a comprehensive understanding of establishing a backend capable of executing CRUD operations (Create, Read, Update, Delete) in a MongoDB database through FastAPI.

Prerequisites

Before we dive in, make sure you have the following installed:

  • Python 3.7+ (preferably 3.8+ for async support)
  • FastAPI (pip install fastapi)
  • MongoDB (community edition or Atlas for cloud-hosted MongoDB)
  • PyMongo (pip install pymongo)
  • An understanding of Python and basic web APIs concepts

Setting Up FastAPI and MongoDB Integration

1. Project Setup

Start by creating a new directory for your project and setting up a virtual environment (optional but recommended)

mkdir fastapi-mongodb
cd fastapi-mongodb
python -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`

2. Install Dependencies

Install FastAPI, Pydantic (for data validation), and PyMongo

pip install fastapi pymongo pydantic

3. Create FastAPI App

Create a file named main.py and define your FastAPI application

from fastapi import FastAPI
from pymongo import MongoClient
app = FastAPI()

# MongoDB connection
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]
@app.get("/")
async def read_root():
return {"message": "Welcome to FastAPI with MongoDB"}
# Implement CRUD operations here

4. Implement CRUD Operations

Now, let’s add CRUD operations to interact with MongoDB:

from fastapi import HTTPException
from pydantic import BaseModel
from bson import ObjectId

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


# Create operation
@app.post("/items/")
async def create_item(item: Item):
result = collection.insert_one(item.dict())
return {"id": str(result.inserted_id), **item.dict()}

# Read operation
@app.get("/items/{item_id}")
async def read_item(item_id: str):
item = collection.find_one({"_id": ObjectId(item_id)})
if item:
return item
raise HTTPException(status_code=404, detail="Item not found")

# Update operation
@app.put("/items/{item_id}")
async def update_item(item_id: str, item: Item):
result = collection.replace_one({"_id": ObjectId(item_id)}, item.dict())
if result.modified_count == 1:
return {"message": "Item updated successfully"}
raise HTTPException(status_code=404, detail="Item not found")

# Delete operation
@app.delete("/items/{item_id}")
async def delete_item(item_id: str):
result = collection.delete_one({"_id": ObjectId(item_id)})
if result.deleted_count == 1:
return {"message": "Item deleted successfully"}
raise HTTPException(status_code=404, detail="Item not found")

5. Run the FastAPI App

Run your FastAPI application with Uvicorn (or your preferred ASGI server):

uvicorn main:app --reload

Conclusion

Congratulations! You’ve successfully integrated FastAPI with MongoDB to create a robust RESTful API. In this article, we covered setting up FastAPI, connecting to a MongoDB database, and implementing CRUD operations. Remember, FastAPI’s async support can further enhance performance for handling concurrent requests.

Next steps could include adding authentication, data validation with Pydantic, handling relationships between MongoDB collections, or deploying your API to a cloud platform like AWS or Heroku.

FastAPI and MongoDB together provide a powerful combination for building modern web APIs that are not only fast and scalable but also maintainable and easy to extend. Happy coding!

--

--