How to launch a fast API application with a NoSQL database

0 Shares
0
0
0
0

Introduction

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 guide 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 choice for applications that need to manage diverse and complex data structures.

Prerequisites
  • A server running Ubuntu with a non-root user with sudo privileges and an active firewall. .
  • Introduction to the Linux command line
  • Run sudo apt-get update in the Ubuntu terminal to ensure that your system has the latest versions and security updates for the software available in the repositories configured on your system.

These instructions are valid for the latest Ubuntu releases: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using an Ubuntu version <= 18.04, we recommend upgrading to the latest version as Ubuntu no longer supports these versions.

Step 1 – Set up the Python environment on your machine

Throughout this tutorial, we will use the python3 package to run commands. The latest version of Ubuntu comes with Python 3 installed, so to verify its installation, run the following command:

python3 --version

If the error returns, you can install/reinstall the package by running:

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 an Ubuntu version < 24.04, you do not need to create a virtual environment, but it is a good practice to separate your project dependencies.

Starting with Python 3.11 and pip 22.3, there is a new PEP 668 that states that Python base environments should be marked as "externally managed", meaning that you cannot successfully use pip to install packages unless you are working in a virtual environment.

In this step, you will 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 set of commands in the terminal:

sudo apt-get install python3-venv

This will install the venv package required to create a virtual environment.

python3 -m venv fastapi-env

This command creates a virtual environment fastapi-env in your working directory. To start working inside this environment, you need to enable it.

source fastapi-env/bin/activate

On successful execution, you will see the terminal prefix as follows:

(fastapi-env) user@machine:~$

You can now start installing the required dependencies inside this virtual environment.

Step 3 – Install the required libraries and packages

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

Let's start by installing fastapi which is required to build your FastAPI application and 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 your FastAPI, you will need to install the engine, which is an asynchronous Python driver for MongoDB.

pip install motor

Step 4 – Install and setup MongoDB on Ubuntu

To install MongoDB on an Ubuntu machine, 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.list

On successful execution, this parameter returns echo. Now do it quickly:

sudo apt-get update

This ensures that you get the latest updates once you set up your MongoDB keys.

Next, you need to install an openssl dependency on your system, which is required to install 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.deb

When 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 mongod

You 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 a FastAPI application

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

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.mycollection

Assuming the mydatabase collection is populated with some data, you will now create a main.py that will hold your application logic. In the FastAPI application below, a database connection is defined using the database.py paths for AI prediction. Using these paths, the input is validated.

nano main.py

In the text editor, write the logic:

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

Here is a summary of what this program does:

  • Linear Regression Model from sklearn: This model predicts an output based on an input feature.
  • Input data from Pydantic model: This structure defines the expected input for the prediction endpoint. In this case, it is a float.
  • Input data from Pydantic model: This defines the expected input for the prediction endpoint. In this case, it is a float.

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

You can use tools like curl or Postman to call an endpoint that predicts a value based on your input.

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

Step 7 [Optional] – Run the application using Docker Compose

You can containerize your application and run it using docker-compose. Containerizing your application simplifies the deployment process and makes your application easier to deploy, scale, and maintain.

Result

In this tutorial, you learned how to successfully launch a FastAPI application with MongoDB, creating 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-powered applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like