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

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

FastAPI is a Python-based web framework known for its speed and simplicity, while NoSQL databases excel in handling unstructured or semi-structured data with ease. AccuWeb.Cloud provides flexible and robust hosting solutions and offers an excellent platform for deploying such applications. With its ability to support containerized workloads, provide seamless database management, and ensure optimal performance, AccuWeb.Cloud is perfectly suited for developers seeking reliable infrastructure.

This guide will walk you through the entire process of setting up a FastAPI application with a NoSQL database on AccuWeb.Cloud. From creating the environment and configuring FastAPI to deploying it with a NoSQL backend, this tutorial is for developers looking to harness the best of modern web application development and hosting.

Introduction to FastAPI and NoSQL Databases

What is FastAPI?

FastAPI is a Python web framework that simplifies creating RESTful APIs. Its standout features include:

  • Built-in support for asynchronous programming.
  • Automatic generation of OpenAPI documentation.
  • Integration with Pydantic for data validation.

Why Use NoSQL Databases?

NoSQL are non-relational databases that store data in flexible, schema-less formats like JSON or key-value pairs. Their advantages include:

  • Scalability: Designed for distributed systems.
  • Flexibility: Supports unstructured and semi-structured data.
  • Performance: Optimized for high read/write throughput.

Steps to Set Up an Environment with Python and MongoDB Containers

Step 1: Set up Python and MongoDB containers for your application and database. This environment ensures seamless communication between your application and the database. You can create this setup using the AccuWeb.Cloud dashboard.

Python and MongoDB containers

Step 2: After creating the environment, connect to your node securely through the Web SSH Gateway provided by AccuWeb.Cloud. This allows you to manage the virtual environment where Python and MongoDB are deployed.

Web SSH gateway

Step 3: Begin by creating a directory for your project and navigating into it:

mkdir fastapi-nosql
cd fastapi-nosql

Step 4: Set up a Python virtual environment to isolate your dependencies:

python3 -m venv venv
source venv/bin/activate # For Linux/Mac
venv\Scripts\activate # For Windows

Step 5: Navigate to your project directory and activate the Python virtual environment:

apache@node11449 fastapi ~/fastapi nosql $ source venv/bin/activate
(venv) apache@node11449 fastapi ~/fastapi nosql $

Ensure the virtual environment is activated before proceeding.

Virtual environment

Step 6: Install the necessary packages, including FastAPI, Uvicorn (a lightweight ASGI server), and motor (an async MongoDB driver):

pip install fastapi uvicorn motor

This command installs the necessary package for connecting and performing operations on MongoDB.

Install packages

Step 7: Create a Python Script to Connect to MongoDB. Navigate to your application directory:

(venv) apache@node11449 fastapi ~/fastapi nosql $ cd app/
(venv) apache@node11449 fastapi ~/fastapi nosql/app $

Now, create a Python script (e.g., ‘database.py‘) to connect to MongoDB. Below is a sample script:

from motor.motor_asyncio import AsyncIOMotorClient
# MongoDB connection string
DATABASE_URL = “mongodb://admin:PSLafq12966@node11448 fastapi.us accuweb.cloud/admin?authSource=admin”
# Initialize MongoDB client
client = AsyncIOMotorClient(DATABASE_URL)
# Specify the database
database = client[“fastapi_db”]
# Example message to verify the connection
print(“Connected to MongoDB successfully!”)

Explanation of the Script:

‘AsyncIOMotorClient’: Connects to the MongoDB server using the provided connection string. Replace ‘admin’, ‘PSLafq12966’, ‘node11448 fastapi.us accuweb.cloud’, and ‘fastapi_db’ with your actual credentials and database details.

The script verifies the connection by attempting to connect to the database and prints a success message.

Connect to the database

Step 8: Execute the script using the Python interpreter:

(venv) apache@node11449 fastapi ~/fastapi nosql/app $ python database.py

Connected to MongoDB successfully!

A success message, “Connected to MongoDB successfully!” confirms the connection to your MongoDB server.

Confirms to connect MongoDB server

This workflow ensures that your Python application can securely communicate with the MongoDB instance hosted on AccuWeb.Cloud. By activating the virtual environment, and running the connection script, your setup is verified and ready for further development.

Installing and Configuring FastAPI

Step 1: Set Up the Project Structure and Organize your project into a modular structure:

fastapi-nosql/

├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── database.py
│ ├── models.py
│ ├── routes/
│ ├── __init__.py
│ ├── item_routes.py

├── requirements.txt

Set up the project structure

Step 2: Create the ‘main.py‘ File and add the following code.

main.py‘ serves as the entry point for your application:

from fastapi import FastAPI
from app.routes.item_routes import router as item_routerapp = FastAPI()@app.get(“/”)
def read_root():
return {“message”: “Welcome to the FastAPI NoSQL App”}# Include API routes
app.include_router(item_router, prefix=”/api/v1/items”, tags=[“Items”])

Set up the project structure

Designing the Application Architecture

An organized application improves scalability and maintainability. The architecture will include:

  • Models: Define the data structure.
  • Routes: Handle API endpoints.
  • Database Layer: Manage the connection and queries.

Building Models for Data Representation

Create ‘models.py‘ and add the following code.

from pydantic import BaseModel
from typing import Optionalclass Item(BaseModel):
id: Optional[str] = None
name: str
description: str
price: float
available: bool = True

Set up the project structure

Creating API Endpoints for CRUD Operations

Create ‘item_routes.py‘ and add the following code.

from fastapi import APIRouter, HTTPException
from app.models import Item
from app.database import databaserouter = APIRouter()@router.post(“/”)
async def create_item(item: Item):
item_dict = item.dict()
result = await database[“items”].insert_one(item_dict)
return {“id”: str(result.inserted_id)}@router.get(“/{item_id}”)
async def read_item(item_id: str):
item = await database[“items”].find_one({“_id”: item_id})
if not item:
raise HTTPException(status_code=404, detail=”Item not found”)
return item
@router.put(“/{item_id}”)
async def update_item(item_id: str, item: Item):
result = await database[“items”].update_one({“_id”: item_id}, {“$set”: item.dict()})
if result.modified_count == 0:
raise HTTPException(status_code=404, detail=”Item not found”)
return {“message”: “Item updated successfully”}@router.delete(“/{item_id}”)
async def delete_item(item_id: str):
result = await database[“items”].delete_one({“_id”: item_id})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail=”Item not found”)
return {“message”: “Item deleted successfully”}

CRUD Operations

Testing the Application

Step 1: Run the Application

uvicorn app.main:app –reload

Testing the application

Test with Swagger UI: Visit ‘http://127.0.0.1:8000/docs’.

Test with ‘curl’ or Postman:

Create an Item: curl -X POST “http://127.0.0.1:8000/api/v1/items/” \
-H “Content-Type: application/json” \
-d ‘{“name”: “Laptop”, “description”: “Gaming laptop”, “price”: 1200.99}’

Adding Authentication to Secure the API

Secure the API using OAuth2 or API keys. FastAPI supports authentication through ‘fastapi.security‘.

Example:

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBeareroauth2_scheme = OAuth2PasswordBearer(tokenUrl=”token”)@app.get(“/protected-route”)
async def protected_route(token: str = Depends(oauth2_scheme)):
if token != “expected-token”:
raise HTTPException(status_code=401, detail=”Invalid token”)
return {“message”: “Secure content”}

Conclusion

Setting up a FastAPI application with a NoSQL database on AccuWeb.Cloud brings together the best of development efficiency and hosting reliability. FastAPI simplifies building APIs with its asynchronous programming support, automatic data validation, and built-in documentation generation, making it a developer-friendly choice for modern web applications pairing it with a NoSQL database like MongoDB ensures flexibility, scalability, and the ability to handle diverse data types effectively.

AccuWeb.Cloud complements this setup by offering a robust and scalable hosting platform. Deploying your application on AccuWeb.Cloud ensures that it operates smoothly handles traffic efficiently and remains accessible to end users without downtime. By following this guide, you’ve learned how to: Set up and configure FastAPI for API development, Integrate and use a NoSQL database for efficient data storage, and deploy your application on AccuWeb.Cloud for optimal performance and scalability.