Introduction
When processing Python applications, FastAPI stands retired arsenic a apical prime for building high-performance solutions. It offers speed, simplicity, and support for asynchronous programming, making it perfect for processing modern, scalable applications. In this tutorial, we will locomotion you done the process of mounting up a FastAPI exertion pinch a NoSQL database. When it comes to storing and managing data, NoSQL databases connection elasticity and scalability, making them a awesome fir doe applications that request to grip divers and analyzable information structures.
Prerequisites
Before you begin, you request to guarantee you person the following:
-
A server moving Ubuntu on pinch a non-root personification pinch sudo privileges and an progressive firewall. For guidance connected really to group this up, please take your distribution from this list and travel our first server setup guide. Please guarantee to activity pinch a supported version of Ubuntu.
-
Familiarity pinch the Linux bid line. For an preamble aliases refresher to the bid line, you tin sojourn this guideline connected Linux bid statement primer.
-
Run sudo apt-get update successful the Ubuntu terminal to guarantee your strategy has the latest versions and information updates for the package disposable from the repositories configured connected your system.
These instructions are valid for the astir caller versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are utilizing Ubuntu type <= 18.04, we urge you upgrade to a much latest type since Ubuntu nary longer provides support for these versions. This postulation of guides will thief you successful upgrading your Ubuntu version.
Step 1 - Set Up Python Environment connected Your Machine
Throughout this tutorial, we will beryllium utilizing the python3 package to tally commands. The latest Ubuntu versions travel pinch Python 3 installation, truthful to verify its installation, tally the pursuing command:
python3 --versionIn lawsuit this returns an error, you tin install/re-install the package by running:
sudo apt-get install python3Next, you request to instal the pip to instal Python packages and their limitations successful a unafraid manner.
sudo apt-get install python3-pipStep 2 - Create Virtual Environment
If you are utilizing Ubuntu type < 24.04, you do not request to create a virtual situation but it’s a bully believe to isolate your project’s dependencies.
Starting from Python 3.11 and pip 22.3, there’s a caller PEP 668 that states the marking of Python guidelines environments arsenic “externally managed”, which intends you won’t beryllium capable to usage pip to instal packages successfully unless you activity wrong a virtual environment.
In this step, you will create a virtual situation for your task that will isolate your project’s limitations to debar imaginable conflicts betwixt different package versions. Run the pursuing group of commands successful the terminal:
sudo apt-get install python3-venvThis will instal the required venv package required to create a virtual environment.
python3 -m venv fastapi-envThis bid will create a virtual situation fastapi-env wrong your moving directory. To commencement moving wrong this environment, you request to activate it.
source fastapi-env/bin/activateOn successful execution, you will spot the terminal punctual prefixed for illustration this:
(fastapi-env) user@machine:~$Now, you tin commencement installing the required limitations wrong this virtual environment.
Step 3 - Install Required Libraries and Packages
In this step, you will beryllium installing a fewer packages and libraries that are required to successfully travel this tutorial.
Let’s commencement by installing fastapi which is required to build your FastAPI exertion and uvicorn that is required to tally the FastAPI application.
pip install fastapi uvicornIn this tutorial, we will usage MongoDB arsenic the NoSQL database. To interact pinch MongoDB from wrong your FastAPI, you request to instal motor, which is an asynchronous Python driver for MongoDB.
pip install motorStep 4 - Install and Set Up MongoDB connected Ubuntu
To instal MongoDB connected your Ubuntu machine, tally the pursuing group of commands successful 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.listOn successful execution, this returns the echo parameter. Now, do a quick:
sudo apt-get updateThis will guarantee you get the latest updates aft mounting up MongoDB keys.
Next up, you request to instal an openssl dependency connected your strategy that is required for MongoDB installation.
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.debOn execution, you will beryllium asked to restart services. After restarting, instal MongoDB utilizing the pursuing command:
sudo apt-get install -y mongodbStart and alteration MongoDB services:
sudo systemctl commencement mongod sudo systemctl enable mongodYou tin cheque the MongoDB work position and trial the relationship by moving the pursuing commands:
sudo systemctl position mongod mongo --eval 'db.runCommand({connectionStatus: 1})'Step 5 - Create FastAPI Application
The adjacent measurement is to create a FastAPI application. In your moving directory, create a database.py file:
nano database.pyThis opens an quiet matter editor. Write your database relationship logic here.
database.py
from motor.motor_asyncio import AsyncIOMotorClient MONGO_DETAILS = "mongodb://localhost:27017" client = AsyncIOMotorClient(MONGO_DETAILS) db = client.mydatabase collection = db.mycollectionAssuming mycollection of mydatabase is populated pinch immoderate data, you now create a main.py that holds your application’s logic. In the pursuing FastAPI app, a database relationship is established utilizing database.py routes for AI prediction are defined. Using these routes, input is validated.
nano main.pyIn the matter editor, constitute the logic:
main.py
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() x = np.array([[1], [2], [3], [4], [5]]) y = np.array([2, 4, 6, 8, 10]) model = LinearRegressions() model.fit(x, y) class InputData(BaseModel): feature: float @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)) @app.get("/items/") async def get_item(): items = [] async for point in collection.find(): items.append(item) return items @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 simply a breakdown of what this exertion does:
- Linear Regression Model from sklearn: This exemplary predicts an output based connected a azygous input feature.
- InputData from Pydantic Model: This defined the expected input building for the prediction endpoint. In this case, it’s a float.
- MongoDB Routes: The routes /items/ and POST /items/ let you to retrieve and insert items into your MongoDB collection.
Step 6 - Run FastAPI Application
To successfully tally this application, you request to instal the libraries and packages utilized successful the application.
pip install pydantic scikit-learn numpyNow, usage the pursuing bid to tally this application:
uvicorn main:app --reloadThe output of this bid will be:
Output
INFO: Will watch for changes successful these directories: ['/path/to/your/project'] INFO: Uvicorn moving connected http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [XXXXX] utilizing statreload INFO: Started server process [XXXXX] INFO: Waiting for exertion startup. INFO: Application startup complete.FastAPI automatically generated an interactive API archiving utilizing Swagger UI. You tin entree it by navigating to http://127.0.0.1:8000/docs.
You tin usage devices for illustration curl aliases Postman to telephone the endpoint that predicts a worth based connected your input.
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 tin containerize your exertion and tally it utilizing docker-compose. Containerizing your exertion streamlines the deployment process by making your exertion easier to deploy, scale, and maintain. To specify your exertion arsenic a Dockerfile, travel the steps mentioned successful Deploy FastAPI Application utilizing Docker Compose.
Conclusion
In this tutorial, you learned really to successfully group up a FastAPI exertion pinch MongoDB, creating a elemental AI-based app tin of storing and retrieving input predictions.
The operation of FastAPI and a NoSQL database offers a powerful and elastic situation for building and scaling AI-driven applications.