Using FastAPI with MongoDB: A Step-by-Step Guide

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python based on standard Python type hints. MongoDB, on the other hand, is a popular NoSQL database that stores data in a flexible, JSON - like format called BSON. Combining FastAPI with MongoDB can create a powerful backend system that is both scalable and efficient. This guide will walk you through the process of integrating FastAPI with MongoDB step - by - step, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Prerequisites
  2. Setting up the Project
  3. Connecting to MongoDB
  4. Defining Data Models
  5. Creating API Endpoints
  6. Testing the API
  7. Common Practices and Best Practices
  8. Conclusion
  9. References

Prerequisites

  • Python 3.7 or higher installed on your system.
  • Basic knowledge of Python, FastAPI, and MongoDB.
  • pip package manager to install necessary libraries.

Setting up the Project

  1. Create a Virtual Environment:
    • Open your terminal and run the following commands:
    python -m venv fastapi_mongo_env
    source fastapi_mongo_env/bin/activate  # For Linux/Mac
    fastapi_mongo_env\Scripts\activate  # For Windows
    
  2. Install Dependencies:
    • Install fastapi, uvicorn (a server for running FastAPI applications), and pymongo (the official MongoDB driver for Python).
    pip install fastapi uvicorn pymongo
    

Connecting to MongoDB

  1. Import the Required Libraries:
    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.

Defining Data Models

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).

Creating API Endpoints

  1. 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.

  2. 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
    

Testing the API

  1. Run the FastAPI Application:

    • In your terminal, run the following command:
    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.

  2. Use a Tool like Postman or cURL:

    • To create an item using 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}'
    
    • To get an item by ID using cURL:
    curl -X GET "http://127.0.0.1:8000/items/your_item_id"
    

Common Practices and Best Practices

Common Practices

  • Error Handling: Always handle potential errors when interacting with MongoDB, such as connection errors, duplicate key errors, etc.
try:
    result = collection.insert_one(item_dict)
except Exception as e:
    return {"error": str(e)}
  • Input Validation: Use Pydantic models for input validation. It ensures that the data received by the API is in the correct format.

Best Practices

  • Indexing: Create appropriate indexes in MongoDB to improve query performance, especially for fields that are frequently used in queries.
collection.create_index("name")
  • Connection Pooling: pymongo already has connection pooling built - in, but make sure to manage your connections properly to avoid resource exhaustion.
  • Security: Use authentication and authorization mechanisms in MongoDB. For example, use username and password to connect to the database instead of connecting without authentication.

Conclusion

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.

References