Tutorials  /  AI/ML

How to Set Up a FastAPI Application with a NoSQL Database

Ccentron Redaktion · February 2025 ·7 min read ·AI/ML, Tutorial

When developing Python applications, FastAPI stands out as a top choice for building high-performance solutions. It offers speed, simplicity, and support for asynchronous programming, making it ideal for developing modern, scalable applications. In this tutorial, we will walk you through the process of setting up a FastAPI application with a NoSQL database. When it comes to storing and managing data, NoSQL databases offer flexibility and scalability, making them a great fit for applications that need to handle diverse and complex data structures.

GPU

Need more GPU power for this project?

Dedicated NVIDIA GPUs (RTX A4000 to A100) from German data centers – from €92.59/month, billed by the hour, ready in minutes. Rent a GPU server →

Prerequisites

Before you begin, you need to ensure you have the following:

  • A server running Ubuntu along with a non-root user with sudo privileges and an active firewall. For guidance on how to set this up, please choose your distribution from this list and follow our initial server setup guide. Please ensure to work with a supported version of Ubuntu.
  • Familiarity with the Linux command line. For an introduction or refresher to the command line, you can visit this guide on Linux command line primer.
  • Run sudo apt-get update in the Ubuntu terminal to ensure your system has the latest versions and security updates for the software available from the repositories configured on your system.
  • These instructions are valid for the most recent versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using Ubuntu version <= 18.04, we recommend you upgrade to a more recent version since Ubuntu no longer provides support for these versions. This collection of guides will help you in upgrading your Ubuntu version.

Step 1 - Set Up Python Environment on Your Machine

Throughout this tutorial, we will be using the python3 package to run commands. The latest Ubuntu versions come with Python 3 installation, so to verify its installation, run the following command:

Console
python3 --version

In case this returns an error, you can install/reinstall the package by running:

Console
sudo apt-get install python3

Next, you need to install the pip to install Python packages and their dependencies in a secure manner.

Code
sudo apt-get install python3-pip

Step 2 - Create Virtual Environment

If you are using Ubuntu version < 24.04, you do not need to create a virtual environment but it’s a good practice to isolate your project’s dependencies.

Starting from Python 3.11 and pip 22.3, there’s a new PEP 668 that states the marking of Python base environments as “externally managed,” which means you won’t be able to use pip to install packages successfully unless you work inside a virtual environment.

To create a virtual environment for your project that will isolate your project’s dependencies to avoid potential conflicts between different package versions, run the following commands:

Console
sudo apt-get install python3-venv
python3 -m venv fastapi-env
source fastapi-env/bin/activate

On successful execution, you will see the terminal prompt prefixed like this:

Code
(fastapi-env) user@machine:~$

Step 3 - Install Required Libraries and Packages

In this step, you will be installing a few packages and libraries that are required to successfully follow this tutorial.

Let’s start by installingfastapiwhich is required to build your FastAPI application anduvicornthat is required to run the FastAPI application.

Console
pip install fastapi uvicorn
pip install motor

We will use MongoDB as the NoSQL database. To interact with MongoDB from within your FastAPI, you need to install motor, which is an asynchronous Python driver for MongoDB.

Step 4 - Install and Set Up MongoDB on Ubuntu

Install MongoDB by running:

Console
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.list

On successful execution, this returns the echo parameter. Now, do a quick:

Console
sudo apt-get update

This will ensure you get the latest updates after setting up MongoDB keys.

Next up, you need to install an OpenSSL dependency on your system that is required for MongoDB installation.

Console
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.deb

On execution, you will be asked to restart services. After restarting, install MongoDB using the following command:

Console
sudo apt-get install -y mongodb

Start and enable MongoDB services:

Console
sudo systemctl start mongod
sudo systemctl enable mongod

You can check the MongoDB service status and test the connection by running the following commands:

Console
sudo systemctl status mongod
mongo --eval 'db.runCommand({connectionStatus: 1})'

Step 5 - Create a FastAPI Application

The next step is to create a FastAPI application. In your working directory, create a database.py file:

Code
nano database.py

This opens an empty text editor. Write your database connection logic here.

Console
# database.py
from motor.motor_asyncio import AsyncIOMotorClient

MONGO_DETAILS = "mongodb://localhost:27017"

client = AsyncIOMotorClient(MONGO_DETAILS)

db = client.mydatabase

collection = db.mycollection

Assuming mycollection of mydatabase is populated with some data, you now create a main.py file that holds your application’s logic.

Code
nano main.py

In the text editor, write the logic for your FastAPI application:

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_item

Application Breakdown

  • Linear Regression Model from Scikit-learn: This model predicts an output based on a single input feature.
  • InputData from Pydantic: Defines the expected input structure for the prediction endpoint. In this case, it’s a float.
  • MongoDB Routes:
    • The GET /items/ route allows retrieval of stored items from MongoDB.
    • The POST /items/ route allows adding new items to MongoDB.

Step 6 - Run FastAPI Application

To successfully run this application, you need to install the required libraries and packages used in the application.

Console
pip install pydantic scikit-learn numpy

Now, use the following command to run this application:

Code
uvicorn main:app --reload

Application Output

When you run the above command, the terminal will display output similar to this:

Code
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 automatically generates an interactive API documentation using Swagger UI. You can access it by navigating to http://127.0.0.1:8000/docs.

Test the API Endpoint

You can use curl or Postman to send a request to the endpoint and predict a value based on your input. Use the following command:

Console
curl -X POST "http://127.0.0.1:8000/predict/" -H "Content-type: application/json" -d '{"feature": 3}'

Step 7 [OPTIONAL] - Run Application Using Docker Compose

You can containerize your application and run it using Docker Compose. Containerizing your application streamlines the deployment process, making it easier to deploy, scale, and maintain.

Conclusion

In this tutorial, you learned how to successfully set up a FastAPI application with MongoDB, creating a simple AI-based app capable of storing and retrieving input predictions.

The combination of FastAPI and a NoSQL database offers a powerful and flexible environment for building and scaling AI-driven applications.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie AI/ML
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren