Unlock the Power of Self-Hosting with FastAPI and MongoDB on Ubuntu 24.04
In today’s digital landscape, self-hosting offers unmatched control and customization over your applications. This comprehensive guide walks you through the seamless integration of FastAPI with MongoDB on Ubuntu 24.04. You’ll dive into the nuances of setting up your own API and executing CRUD operations effortlessly. If you’re ready to take charge of your hosting environment, keep reading to unleash the capabilities of FastAPI!
What You Will Learn
By the end of this tutorial, you will have:
- Installed FastAPI and MongoDB on Ubuntu 24.04.
- Set up a virtual environment for your FastAPI project.
- Established a simple CRUD API with FastAPI and MongoDB.
Prerequisites
- An Ubuntu 24.04 system.
- A non-root user with administrator privileges.
Installing MongoDB
Before diving into FastAPI, it’s essential to have MongoDB installed. Begin by updating your package index and installing the necessary tools:
sudo apt update && sudo apt install gnupg curl -yAfterward, add the GPG key and the MongoDB repository:
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmorecho "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.listNow install MongoDB:
sudo apt update && sudo apt install mongodb-orgStart the MongoDB service and enable it to run at startup:
sudo systemctl enable --now mongodCheck the status to confirm it’s running:
sudo systemctl status mongodSetting Up a Python Environment
With MongoDB in place, the next step is to configure your Python environment:
sudo apt install python3 python3-pip python3-venvCreate and navigate into a project directory:
mkdir -p ~/app; cd ~/appNow create and activate a virtual environment:
python3 -m venv .venvsource .venv/bin/activateCreating Your FastAPI Project
Install FastAPI and Uvicorn:
pip3 install fastapi uvicornCreate the necessary project structure:
mkdir -p server/{models,routes} && touch main.py server/{app.py,database.py} server/models/itemModels.py server/routes/item.pyBuilding Your API
Defining the Application
Open the server/app.py file and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello FastAPI!"}Implementing CRUD Operations
The next step is to implement CRUD operations in server/database.py. You will need the motor MongoDB driver:
pip3 install motorIn the database.py file, add your MongoDB connection logic:
from motor.motor_asyncio import AsyncIOMotorClient
MONGODB_HOST = "mongodb://localhost:27017"
connection = AsyncIOMotorClient(MONGODB_HOST)
database = connection.items
item_collection = database.get_collection("item_collection")Creating Data Models with Pydantic
Utilize pydantic for data validation. Inside server/models/itemModels.py, define your item schema:
from pydantic import BaseModel, Field
from typing import Optional
class Item(BaseModel):
name: str
category: str
stocks: int
price: int = Field(gt=0)
Setting Up API Routes
To enable interaction with your data, define API endpoints in server/routes/item.py. You will create the endpoints for adding, retrieving, updating, and deleting items.
@router.post("/")for adding new items.@router.get("/")for retrieving all items.@router.get("/{id}")for getting a specific item.@router.put("/{id}")for updating items.@router.delete("/{id}")for deleting items.
Testing Your API
Run your FastAPI application:
python3 main.pyNavigate to http://SERVERIP:8080/docs to interact with your API documentation, elegantly provided by Swagger UI.
Conclusion
Congratulations! You’ve successfully self-hosted an API using FastAPI and MongoDB on Ubuntu 24.04. This guide not only empowered you to leverage the full potential of self-hosting but also allowed you to experiment with building and managing your API. With FastAPI’s performance and MongoDB’s flexibility, you’re now equipped to create robust applications. Don’t hesitate to explore more features and expand your API further!
FAQ
Question 1: What are the benefits of self-hosting?
Self-hosting provides greater control over data, customization options, and enhanced privacy. Users can manage their server settings without dependency on third-party services.
Question 2: Can I use other databases with FastAPI?
Absolutely! FastAPI is compatible with various databases like PostgreSQL, MySQL, and SQLite. You can integrate them easily based on your application requirements.
Question 3: How do I secure my FastAPI application?
Consider implementing authentication and authorization strategies, such as OAuth2. Also, ensure to implement HTTPS for secure data transmission when deploying your application.

