Guide to Installing FastAPI with MongoDB on Ubuntu 24.04

Introduction

FastAPI has rapidly become a favorite framework for building modern, high-performance web APIs in Python. Combined with MongoDB—a flexible, document-oriented NoSQL database—it provides developers with a potent stack for rapid application development. In this guide, we’ll walk through the installation and configuration of FastAPI alongside MongoDB on Ubuntu 24.04. Whether you’re building microservices, RESTful APIs, or full-stack applications, this tutorial covers everything from setting up your environment to running your first FastAPI app connected to MongoDB.

Prerequisites

Before you begin, ensure you have the following:

  • A server or virtual machine running Ubuntu 24.04 with sudo privileges.
  • Basic familiarity with Linux command-line operations.
  • An updated Python 3 installation (preferably Python 3.8 or higher).
  • Internet access for downloading packages and updates.

Step-by-Step Installation

Follow these steps to install and configure FastAPI with MongoDB.

1. Update Your System

First, update your package list and upgrade existing packages to ensure your system is current:

sudo apt update && sudo apt upgrade -y

2. Install Python and Set Up a Virtual Environment

If Python isn’t installed, install it along with the virtual environment package:

sudo apt install python3 python3-venv python3-pip -y

Create and activate a virtual environment to isolate your project dependencies:

python3 -m venv fastapi-env
source fastapi-env/bin/activate

3. Install FastAPI and Uvicorn

FastAPI is best served with Uvicorn, an ASGI server that runs your application. Install both using pip:

pip install fastapi uvicorn

4. Install and Configure MongoDB

MongoDB will serve as the NoSQL database backend for your application. Follow these steps to install MongoDB on Ubuntu 24.04:

a. Import the MongoDB Public Key

wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

b. Create the MongoDB List File

Create a list file for MongoDB to add its repository:

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

Note: Although the repository URL references "focal" (Ubuntu 20.04), it is often compatible with Ubuntu 24.04. Verify with MongoDB’s official documentation if adjustments are needed.

c. Update and Install MongoDB

sudo apt update
sudo apt install -y mongodb-org

d. Start and Enable MongoDB Service

Enable and start MongoDB to ensure it runs on boot:

sudo systemctl start mongod
sudo systemctl enable mongod

You can check the status of the MongoDB service:

sudo systemctl status mongod

5. Create a Basic FastAPI Application with MongoDB Integration

Create a new Python file (e.g., main.py) in your project directory and add the following sample code:

from fastapi import FastAPI
from pymongo import MongoClient

app = FastAPI()

# Replace with your MongoDB connection details if different
client = MongoClient("mongodb://localhost:27017")
db = client["fastapi_db"]
collection = db["items"]

@app.get("/")
def read_root():
    return {"message": "Welcome to FastAPI with MongoDB!"}

@app.get("/items")
def read_items():
    # Fetch all documents from the collection
    items = list(collection.find({}, {"_id": 0}))
    return {"items": items}

@app.post("/items")
def create_item(item: dict):
    # Insert a new document into the collection
    collection.insert_one(item)
    return {"message": "Item created successfully"}

Install the required MongoDB Python driver:

pip install pymongo

6. Run the FastAPI Application

Start your FastAPI app using Uvicorn:

uvicorn main:app --reload

Visit http://localhost:8000 in your browser to see the welcome message. You can also access the interactive API docs at http://localhost:8000/docs.

Troubleshooting

While setting up FastAPI with MongoDB, you might encounter some common issues:

  • MongoDB Connection Errors:
    Ensure MongoDB is running and listening on the correct port (default is 27017). Use sudo systemctl status mongod to check if the service is active.

  • Dependency Errors:
    If you encounter missing packages or version conflicts, verify that you have activated your virtual environment and that all required packages (like pymongo) are installed.

  • FastAPI Server Issues:
    If Uvicorn fails to start, check for syntax errors in your main.py file. Running the app with --reload can help identify changes that may require a restart.

  • Port Conflicts:
    Ensure that port 8000 is free or specify a different port by using the --port flag with Uvicorn.

Best Practices & Optimization Tips

  • Virtual Environment:
    Always work within a virtual environment to manage dependencies effectively and avoid conflicts.

  • Secure Your Database:
    For production, configure MongoDB with proper authentication and network restrictions. Avoid using default settings that expose the database to public networks.

  • Environment Variables:
    Store sensitive configurations (like database URIs and credentials) in environment variables or configuration files outside your codebase.

  • API Versioning and Documentation:
    Leverage FastAPI’s built-in support for API versioning and auto-generated documentation to maintain a scalable and maintainable project.

  • Monitoring and Logging:
    Implement logging in your FastAPI application to monitor performance and troubleshoot issues effectively. Consider integrating external monitoring tools for a production environment.

Conclusion

Integrating FastAPI with MongoDB on Ubuntu 24.04 equips you with a powerful stack for developing modern web applications. By following this guide, you have set up a clean environment, installed the necessary components, and built a simple yet scalable API. Continue exploring FastAPI’s capabilities and MongoDB’s flexible document model to build robust solutions tailored to your project needs. Happy coding!