Installing FastAPI with MongoDB on Ubuntu 24.04: Comprehensive Guide
This tutorial provides comprehensive steps for Installing FastAPI with MongoDB on Ubuntu 24.04. FastAPI is a modern, high-performance Python web framework, and MongoDB is a NoSQL database that provides flexibility and scalability. When these two are combined, they create a powerful backend solution for web applications.
This guide will take you through the installation and configuration steps for setting up FastAPI with MongoDB on Ubuntu 24.04.
Before you start Installing FastAPI with MongoDB on Ubuntu 24.04, you must log in to your Ubuntu 24.04 server as a non-root user with sudo privileges. You can check out our guide on Creating a Sudo User on Ubuntu 24.04. Then, proceed to the following steps to start your FastAPI setup with MongoDB on Ubuntu 24.04.
Step 1. Install MongoDB on Ubuntu 24.04
First, run the system update and upgrade by using the following commands:
# sudo apt update
# sudo apt upgrade -y
Then, run the command below to install the required packages:
sudo apt install gnupg curl -y
Once you are done, you must add the MongoDB GPG Key and Repository.
Add MongoDB GPY Key and Repository
Now, add the MongoDB server GPG key by using the following command on your Ubuntu 24.04:
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc |
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg
--dearmor
Next, add the MongoDB server repository on Ubuntu 24.04 with the following command:
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
Once you have added the MongoDB repository, you must run the system update:
sudo apt update
Installing MongoDB
You can now use the command below to install your MongoDB server:
sudo apt install mongodb-org -y
Start and Enable MongoDB
At this point, you must start and enable your MongoDB service, which is called mongod, by using the command below:
sudo systemctl enable --now mongod
Then, check that your MongoDB service is active and running on Ubuntu 24.04 with the command below:
sudo systemctl status mongod

Also, you can check for additional information by running the Mongosh command:
mongosh

You can exit by pressing Ctrl + D.
Step 2. Install Python and Virtual Env for FastAPI Setup
At this point, you must install Python and set up the Python virtual environment for your FastAPI setup. First, install Python, Python Pip, and Python Venv by using the command below:
sudo apt install python3 python3-pip python3-venv -y
Then, you must create a new project directory to store your FastAPI project and navigate to it:
mkdir -p ~/app; cd ~/app
Next, set up a virtual environment and activate it with the following commands:
# python3 -m venv fastapi-env
# source fastapi-env/bin/activate
With this, your shell prompt will become like this:

Step 3. Install FastAPI in Python Virtual Env
Now, from your virtual environment, run the command below to install FastAPI and uvicorn, which is the implementation of the ASGI (Asynchronous Server Gateway Interface) web server in Python, and install motor, which is the MongoDB driver:
pip3 install fastapi uvicorn motor

Step 4. Create a FastAPI Application
At this point, you must create a database.py file with your desired text editor, like Vi editor or Nano editor:
sudo vi database.py
This will open an empty file. You can add your database connection logic to the file. For example:
from motor.motor_asyncio import AsyncIOMotorClient
MONGO_DETAILS = "mongodb://localhost:27017"
client = AsyncIOMotorClient(MONGO_DETAILS)
db = client.mydatabase
collection = db.mycollection
Once you are done, save and close the file.
Next, you must create a main.py that holds your application’s logic:
sudo vi main.py
In this FastAPI app:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sklearn.linear_model import LinearRegression
import numpy as np
from database import collection
app = FastAPI()
# Simple dataset and model
x = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])
model = LinearRegression() # Corrected class name
model.fit(x, y)
# Define the Pydantic model for input validation
class InputData(BaseModel):
feature: float
# Route_1 for predicting the output based on input feature
@app.post("/predict/")
async def predict(input_data: InputData):
try:
prediction = model.predict([[input_data.feature]])
return {"prediction": prediction[0]}
except Exception as ex:
raise HTTPException(status_code=400, detail=str(ex))
# Route_2 to interact with MongoDB
@app.get("/items/")
async def get_item():
items = []
async for item in collection.find():
items.append(item)
return items
# Route_3 to add a new item to MongoDB
@app.post("/items/")
async def create_item(item: dict):
new_item = await collection.insert_one(item) # Insert item
created_item = await collection.find_one({"_id": new_item.inserted_id}) # Correct method name
return created_item
Once you are done, save and close the file.
Step 5. Run FastAPI Application
At this point, you must install the required packages and libraries for running your project with the command below:
pip install pydantic scikit-learn numpy

Then, run your FastAPI app by using the following command:
uvicorn main:app --reload
In the output, you should see:

FastAPI automatically creates interactive API documentation using Swagger UI. You can view it by going to http://127.0.0.1:8000/docs
in your browser.
To test the prediction endpoint, you can use tools like curl or Postman to send requests and get results based on your input:
curl -X POST "http://127.0.0.1:8000/predict/" -H "Content-type: application/json" -d '{"feature": 3}'
Conclusion
In this guide, you learned how to build a FastAPI application integrated with MongoDB, creating a simple AI-powered system for storing and retrieving predictions. FastAPI, combined with a NoSQL database, provides a fast and scalable solution for developing AI-driven applications efficiently. Installing FastAPI with MongoDB on Ubuntu 24.04 is a great way to start building modern web apps.
Hope you enjoy it. Please subscribe to us on Facebook, Instagram, and YouTube.
You may also like to read the following articles:
Install Podman on Ubuntu 24.04
Install PyCharm on Ubuntu 24.04
Top Linux Desktop Distros for Teams to Access Remotely
Linux kernel 6.14 Features and Release Date
Alternative Solutions
While the provided guide offers a solid approach to Installing FastAPI with MongoDB on Ubuntu 24.04, here are two alternative methods that you could consider, each with its own advantages and disadvantages.
1. Using Docker and Docker Compose
This method leverages containerization to simplify the deployment and management of both FastAPI and MongoDB. Docker allows you to package your application and its dependencies into a single unit, ensuring consistency across different environments.
Explanation:
Instead of installing MongoDB directly on the Ubuntu 24.04 host, you can run it within a Docker container. Similarly, your FastAPI application will reside in another Docker container. Docker Compose then orchestrates these containers, defining their dependencies and networking.
Steps:
-
Install Docker and Docker Compose: If you haven’t already, install Docker and Docker Compose on your Ubuntu 24.04 system.
-
Create a
docker-compose.yml
file: This file will define the services (MongoDB and FastAPI) and their configurations.
version: "3.9"
services:
mongodb:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
fastapi:
build: .
ports:
- "8000:8000"
depends_on:
- mongodb
environment:
DATABASE_URL: mongodb://root:example@mongodb:27017
volumes:
mongodb_data:
- Create a
Dockerfile
for FastAPI: This file will define how to build the FastAPI image.
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
- Update
database.py
: Modify theMONGO_DETAILS
variable to use the Docker service name (mongodb
) and the credentials defined indocker-compose.yml
.
from motor.motor_asyncio import AsyncIOMotorClient
MONGO_DETAILS = "mongodb://root:example@mongodb:27017"
client = AsyncIOMotorClient(MONGO_DETAILS)
db = client.mydatabase
collection = db.mycollection
- Create
requirements.txt
: List the Python dependencies for your FastAPI application.
fastapi
uvicorn
motor
pydantic
scikit-learn
numpy
- Run
docker-compose up -d
: This command will build and start the containers in detached mode.
Advantages:
- Isolation: Containers provide isolation, preventing conflicts between dependencies.
- Reproducibility: Ensures consistent deployments across different environments.
- Scalability: Easier to scale using Docker Swarm or Kubernetes.
Disadvantages:
- Overhead: Containerization adds some overhead compared to running applications directly on the host.
- Complexity: Requires understanding of Docker and Docker Compose.
2. Using MongoDB Atlas (Cloud-Based MongoDB)
This approach eliminates the need to install and manage MongoDB on your own server. MongoDB Atlas is a fully managed cloud database service that handles the infrastructure and maintenance for you.
Explanation:
Instead of installing MongoDB locally, you’ll create a MongoDB Atlas cluster and connect your FastAPI application to it. This offloads the database management tasks, allowing you to focus on developing your application.
Steps:
-
Create a MongoDB Atlas Account: Sign up for a free account on the MongoDB Atlas website.
-
Create a New Cluster: Follow the instructions in the Atlas UI to create a new cluster. Choose a region close to your server for low latency. Configure network access to allow connections from your server.
-
Create a Database User: Create a database user with appropriate permissions for your application.
-
Get the Connection String: Atlas will provide you with a connection string that you can use to connect to your cluster. It will look something like:
mongodb+srv://<username>:<password>@<cluster-url>/mydatabase?retryWrites=true&w=majority
-
Update
database.py
: Modify theMONGO_DETAILS
variable to use the Atlas connection string.
from motor.motor_asyncio import AsyncIOMotorClient
MONGO_DETAILS = "mongodb+srv://<username>:<password>@<cluster-url>/mydatabase?retryWrites=true&w=majority"
client = AsyncIOMotorClient(MONGO_DETAILS)
db = client.mydatabase
collection = db.mycollection
Replace <username>
, <password>
, and <cluster-url>
with the actual values from your Atlas connection string.
- Install
dnspython
: You might need to install thednspython
package, which is required for resolving the MongoDB Atlas SRV record.
pip install dnspython
Advantages:
- Managed Service: Atlas handles all the infrastructure, backups, and maintenance.
- Scalability: Easily scale your database as your application grows.
- Availability: Atlas provides high availability and disaster recovery.
Disadvantages:
- Cost: Atlas is a paid service, although a free tier is available with limitations.
- Dependency: Relies on an external service and internet connectivity.
- Security: Requires careful configuration of network access and authentication.
These alternative solutions offer different approaches to Installing FastAPI with MongoDB on Ubuntu 24.04, each with its own trade-offs. Choosing the right solution depends on your specific requirements, resources, and expertise.