Introduction
When developing Python applications, FastAPI is a great choice with its speed, simplicity, and support for asynchronous programming. In this tutorial, we'll explore setting up FastAPI with a NoSQL database, which offers flexibility and scalability for managing diverse data.
Prerequisites
- Ubuntu Server, a non-root user with sudo access and an enabled firewall.
- Introduction to the Linux command line.
- Order
sudo apt-get updateRun in the Ubuntu terminal to ensure that your system has the latest versions and security updates of the software available in the system repositories.
Note: These instructions are valid for the latest versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using Ubuntu 18.04 or older, we recommend upgrading to a newer version, as Ubuntu no longer supports these versions.
Step 1 – Setting up the Python environment on your system
Throughout this tutorial, we will use the python3 package to run commands. Newer versions of Ubuntu come with Python 3 installed by default, so to verify its installation, run the following command:
python3 --version
If this command returns an error, you can install or reinstall the package by running the following command:
sudo apt-get install python3
Next, you need to install pip to safely install Python packages and their dependencies.
sudo apt-get install python3-pip
Step 2 – Create a virtual environment
If you are using Ubuntu version < 24.04, you do not need to create a virtual environment, but it is a best practice to separate project dependencies.
Starting with Python 3.11 and pip 22.3, a new PEP 668 has been introduced that marks Python base environments as "externally managed", meaning you cannot successfully use pip to install packages unless you are working in a virtual environment. Do it.
In this step, you will create a virtual environment for your project that isolates project dependencies to prevent potential problems between different versions of packages. Run the following commands in the terminal:
sudo apt-get install python3-venv
This command is closed. venv It will install what is needed to create a virtual environment.
python3 -m venv fastapi-env
This command creates a virtual environment called fastapi-env It will create a directory inside your working directory. To start working in this environment, you need to enable it.
source fastapi-env/bin/activate
If successful, you will see the terminal preview displayed as follows:
(fastapi-env) user@machine:~$
Now you can start installing the required dependencies inside this virtual environment.
Step 3 – Install required libraries and packages
In this step, you will install a few packages and libraries that are required to successfully follow this tutorial.
First by installing FastAPI We'll start with what's needed to build your app, and then uvicorn Which is required to run the FastAPI application.
pip install fastapi uvicorn
In this tutorial, we will use MongoDB as a NoSQL database. To interact with MongoDB from within FastAPI, you need to motor Install , which is an asynchronous Python driver for MongoDB.
pip install motor
Step 4 – Install and Setup MongoDB on Ubuntu
To install MongoDB on your Ubuntu system, run the following set of commands in the terminal:
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/mongodb-archive-keyring.gpg] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.listIf successful, this command will return the echo parameter. Now do a quick update:
sudo apt-get update
This ensures that you get the latest updates after setting up your MongoDB keys.
After that, you need to install an openssl dependency on your system, which is necessary for installing MongoDB.
wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb
sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.debAfter running, you will be asked to restart the services. After restarting, install MongoDB using the following command:
sudo apt-get install -y mongodb
Start and enable MongoDB services:
sudo systemctl start mongod
sudo systemctl enable mongodYou can check the status of the MongoDB service and test the connection by running the following commands:
sudo systemctl status mongod
mongo --eval 'db.runCommand({connectionStatus: 1})'
Step 5 – Create FastAPI Application
The next step is to create a FastAPI application. In your working directory, create a file called database.py Create:
nano database.py
This will open a blank text editor. Write your database connection logic here.
from motor.motor_asyncio import AsyncIOMotorClient
MONGO_DETAILS = "mongodb://localhost:27017"
client = AsyncIOMotorClient(MONGO_DETAILS)
db = client.mydatabase
collection = db.mycollectionAssuming that the set mycollection From the database mydatabase It's filled with data, now you need a file main.py Create a class that holds your application logic. In the FastAPI application below, connect to the database via database.py It is established and paths are defined for AI predictions. These paths are used for input validation.
nano main.py
In the text editor, write the following code:
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 = LinearRegressions()
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)
created_item = await collection.fine_one({"_id": new_item.inserted_id})
return created_itemHere is an explanation of how this program works:
- Linear Regression Model from sklearn: This model predicts the output based on an input feature.
- InputData from Pydantic model: This model defines the expected input structure for the prediction endpoint. Here, the input is of type float.
- MongoDB paths: Routes
/items/andPOST /items/They allow you to retrieve and import items from your MongoDB collection.
Step 6 – Run the FastAPI application
To successfully run this program, you need to install the libraries and packages used in the program.
pip install pydantic scikit-learn numpy
Now, use the following command to run this program:
uvicorn main:app --reload
The output of this command will be as follows:
Output
INFO: Will watch for changes in these directories: ['/path/to/your/project']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [XXXXX] using statreload
INFO: Started server process [XXXXX]
INFO: Waiting for application startup.
INFO: Application startup complete.FastAPI has automatically generated interactive API documentation using Swagger UI. You can access it via the address http://127.0.0.1:8000/docs Access it.
You can use tools like curl or Postman to call an endpoint that predicts the value based on your input.
curl -X POST "http://127.0.0.1:8000/predict/" -H "Content-type: application/json" -d '{"feature": 3}'
Result
In this tutorial, you learned how to successfully deploy a FastAPI application with MongoDB and build a simple AI-based application capable of storing and retrieving input predictions.
The combination of FastAPI and NoSQL database provides a powerful and flexible environment for building and scaling AI-based applications.









