Tutorial

How to Set Up a Fast API Application with a NoSQL Database

Published on September 27, 2024

Technical Writer

How to Set Up a Fast API Application with a NoSQL Database

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 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 fir doe applications that need to handle diverse and complex data structures.

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 latest 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:

python3 --version

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

sudo apt-get install python3

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

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.

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 required venv package required to create a virtual environment.

python3 -m venv fastapi-env

This command will create a virtual environment fastapi-env inside your working directory. To start working inside this environment, you need to activate it.

source fastapi-env/bin/activate

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

(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 be installing 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 that is required to run the FastAPI application.

pip install fastapi uvicorn

In this tutorial, 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.

pip install motor

Step 4 - Install and Set Up MongoDB on Ubuntu

To install MongoDB on your Ubuntu machine, run the following set of commands in 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 returns the echo parameter. Now, do a quick:

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.

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:

sudo apt-get install -y mongodb

Start and enable MongoDB services:

sudo systemctl start mongod
sudo systemctl enable mongod

You can check the MongoDB service status 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 database.py file:

nano database.py

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

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 that holds your application’s logic. In the following FastAPI app, a database connection is established using database.py routes for AI prediction are defined. Using these routes, input is validated.

nano main.py

In the text editor, write 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()

# 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 breakdown of what this application does:

  • Linear Regression Model from sklearn: This model predicts an output based on a single input feature.
  • InputData from Pydantic Model: This defined the expected input structure for the prediction endpoint. In this case, it’s a float.
  • MongoDB Routes: The routes /items/ and POST /items/ allow you to retrieve and insert items into your MongoDB collection.

Step 6 - Run FastAPI Application

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

pip install pydantic scikit-learn numpy

Now, use the following command to run this application:

uvicorn main:app --reload

The output of this command will be:

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 navigating to http://127.0.0.1:8000/docs.

You can use tools like curl or Postman to call the 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 Application Using Docker Compose

You can containerize your application and run it using docker-compose. Containerizing your application streamlines the deployment process by making your application easier to deploy, scale, and maintain. To define your application as a Dockerfile, follow the steps mentioned in Deploy FastAPI Application using Docker Compose.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar

Technical Writer

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more