FastAPI & MongoDB on Ubuntu 24.04 – The Ultimate Setup Guide
FastAPI is one of the most efficient and modern Python web frameworks, offering lightning-fast performance for API development. When combined with MongoDB, a highly scalable NoSQL database, it creates a powerful backend for web applications. In this guide, we’ll walk you through setting up FastAPI with MongoDB on Ubuntu 24.04, ensuring a smooth and optimized deployment.
Why Choose FastAPI with MongoDB?
Before jumping into the setup process, let’s understand why FastAPI
and MongoDB make a great combination:
✅ Blazing Fast Performance –
FastAPI is designed for speed, thanks to asynchronous programming and Pydantic
validation.
✅ Scalability & Flexibility – MongoDB is a NoSQL
database that can handle large amounts of data with ease.
✅ Easy Integration – FastAPI works seamlessly with
MongoDB using libraries like Motor (for async operations).
✅ Minimal Boilerplate Code – With FastAPI, you can
build APIs quickly without unnecessary complexity.
Step 1: Update Ubuntu 24.04 and Install Python
Start by updating your Ubuntu 24.04 system to ensure
everything is up to date:
sudo apt update && sudo apt upgrade -y
Next, install Python 3 and pip (Python package manager):
sudo apt install python3 python3-pip -y
Verify the installation:
python3 --version
Step 2: Install FastAPI & Uvicorn
FastAPI requires Uvicorn, an ASGI server to run efficiently.
Install both using pip:
pip3 install fastapi uvicorn
To confirm FastAPI is installed, check its version:
python3 -c "import fastapi;
print(fastapi.__version__)"
Step 3: Install and Configure MongoDB
MongoDB is the database that will store your application
data. Install it using:
sudo apt install mongodb -y
Start and enable MongoDB:
sudo systemctl start mongodb
sudo systemctl enable mongodb
Verify that MongoDB is running:
sudo systemctl status mongodb
Step 4: Connect FastAPI to MongoDB
We need Motor, an asynchronous MongoDB driver, to connect
FastAPI to MongoDB:
pip3 install motor
Now, create a main.py file and add the following FastAPI
connection logic:
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient
app = FastAPI()
# MongoDB Connection
MONGO_URI = "mongodb://localhost:27017"
client = AsyncIOMotorClient(MONGO_URI)
db = client["mydatabase"]
@app.get("/")
async def read_root():
return
{"message": "FastAPI with MongoDB is running!"}
Step 5: Run FastAPI on Ubuntu 24.04
Launch the FastAPI application using Uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
Your API is now running! Open your browser and visit:
For automatic API documentation, visit:
π http://localhost:8000/docs
✅ Final Thoughts
With FastAPI and MongoDB, you now have a powerful and
efficient backend running on Ubuntu 24.04. Whether you’re building a small API
or a large-scale application, this setup ensures speed, scalability, and
flexibility.
Start building your FastAPI-powered applications today!
Comments
Post a Comment