This guide is a composite road map for deployment of a Postgresql database linked to the Fast PI passenger RatA cloud platform that helps host the web apps and organized postgresses QL Database.
You can find a full source code Here.
Deployment context
When deploying the Fast API app connected to the postgrass QL, you need to select a platform that supports web applications and organized databases. It uses the guide render as an example platform as it provides both web hosting and postgrass QL database service in an environment, which straightens your backbone to connect the database.
You can also apply ideas here to other cloud providers, but steps will be different in terms of platform details.
Here’s what we will cover is:
The project structure
If you are making a real world API Phostep You will quickly pour one one forward main.py
The file is necessary to maintain the structure of the modular project.
Here is an example structure we will use in this guide:
FastAPI/
├── database/
│ ├── base.py
│ ├── database.py
│ └── __init__.py
├── fastapi_app/
│ └── main.py
├── items/
│ ├── models/
│ │ ├── __init__.py
│ │ └── item.py
│ ├── routes/
│ │ ├── __init__.py
│ │ └── item.py
│ └── schemas/
│ ├── __init__.py
│ └── item.py
├── models/
│ └── __init__.py
├── orders/
│ ├── models/
│ │ ├── __init__.py
│ │ └── order.py
│ ├── routes/
│ │ ├── __init__.py
│ │ └── order.py
│ └── schemas/
│ ├── __init__.py
│ └── order.py
└── users/
├── models/
│ ├── __init__.py
│ └── user.py
├── routes/
│ ├── __init__.py
│ └── user.py
└── schemas/
├── __init__.py
└── user.py
What will you need before starting
Before diving, make sure you have found:
A free Rat Account (Sign up if you don’t have)
A gut hub or gut lab repository for your Fast API project
Basic acquaintance with azagar, fastep, and gut
Your project structure is similarly configured according to the above instance
Deployment steps
Step 1: Set the local postgrass QL Database
Local Development
psql -U postgres
CREATE DATABASE your_db;
CREATE USER your_user WITH PASSWORD 'your_secure_password';
GRANT ALL PRIVILEGES ON DATABASE your_db TO your_user;
ALTER USER your_user CREATEDB;
\q
After setting your local database, make a .env
File at the root of your project:
DATABASE_URL=postgresql://your_user:your_secure_password@localhost:5432/your_db
Step 2: Set your database connection
Create database/database.py
To manage your Postgrass QL connection with Scalchimi:
This file is very important because it makes the database engine, explains the session management, and provides a dependence function for your routes.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
"""
The engine manages the connection to the database and handles query execution.
"""
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
And add database/base.py
For the base class:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Step 3: Create your Fast API Main Application
Create the Main Fastep application file fastapi_app/main.py
To import all your root modules:
import os
from fastapi import FastAPI, APIRouter
from fastapi.openapi.utils import get_openapi
from fastapi.security import OAuth2PasswordBearer
import uvicorn
from dotenv import load_dotenv
load_dotenv()
from database import Base, engine
import models
from items.routes import item_router
from orders.routes import order_router
from users.routes import user_router
app = FastAPI(
title="Store API",
version="1.0.0",
description="API documentation for Store API"
)
Base.metadata.create_all(bind=engine)
@app.get("/")
async def root():
return {"message": "Welcome to FastAPI Store"}
api_router = APIRouter(prefix="/v1")
api_router.include_router(item_router)
api_router.include_router(order_router)
api_router.include_router(user_router)
app.include_router(api_router)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/v1/auth/login")
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
)
openapi_schema("components")("securitySchemes") = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
}
}
openapi_schema("security") = ({"BearerAuth": ()})
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
if __name__ == "__main__":
port = os.environ.get("PORT")
if not port:
raise EnvironmentError("PORT environment variable is not set")
uvicorn.run("fastapi_app.main:app", host="0.0.0.0", port=int(port), reload=False)
Step 4: Create a file of requirements
In the root of your project, make a requirements.txt
File which contains all the necessary dependence:
fastapi>=0.68.0
uvicorn>=0.15.0
sqlalchemy>=1.4.23
psycopg2-binary>=2.9.1
python-dotenv>=0.19.0
pydantic>=1.8.2
Step 5: Postgrass QL Database Supply on Reader
Login to your render dashboard Dashboard.randar dot com.
Then click ”New +“Top right and select”Postgresql“.
Fill details:
Name:
your-app-db
(Choose the descriptive name)Database:
your_app
(It would be your database name)User: Leave Default (Auto -developed)
Area: Choose the closest to your target users
Plan: Free levels
Save and note the internal database shown after the creation, which will look like this:
postgres://user:password@postgres-instance.render.com/your_app
Step 6: Deploy your Fast PIApp to Rander
With the supply of your database, it’s time to deploy your API. You can do this by following these steps:
In the render dashboard, click “New +“And choose”Web Service“
Connect your Gut Hub/Got Lab Ripozetry
Name your service
Then create the construction settings:
Add your environmental variables:
Finally, click Deploy the web service.
Step 7: Check your API closing points
Once deployed, access your API’s URL (eg, https://your-app-name.onrender.com
,
Navigate /docs
To open the Interactive Sweeger UI, where you can directly test your closing points:
Local development workflow
Even when your app is deployed, you will still need to work locally. The way to maintain a smooth development workflow is:
First, make a local .env
File (do not commit this gut):
DATABASE_URL=postgresql://username:password@localhost:5432/your_local_db
Then install your dependence in a virtual environment:
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Next, run your local server:
python3 -m fastapi_app.main
This command is dynamic __main__
Block in fastapi_app/main.py
Which launches a fast API app using Yukorin. It reads PORT
From your environment, so make sure it’s set (such as, through .env
File)..
Then make changes to your code and test locally before pushing the Gut Hub/Gut Lab forward. You can move forward your changes to mobilize a new deployment on the render.
The best action and indicators
Use database emigration: Add the albux to your own project to manage scheme changes
pip install alembic alembic init migrations
Separate development and production formation:
if os.environ.get("ENVIRONMENT") == "production": else:
Monitor your request:
- Rader provides logs and matrix for your request. You can set alerts for mistakes or high resources.
Improve database questions:
Scale when needed:
- Rader allows you to upgrade your project as your application increases. Consider upgrading your own database plan for production applications.
Common problems and solutions
When deploying the web app on the render, there are usually some problems. Here is another detailed look on them and how you can solve everyone.
Database connection errors:
If your app may not contact the database, check first double that you DATABASE_URL
Environmental variables are correctly configured in your rendering dashboard. Make sure the URL includes the right username, password, host, port, and database name.
Also, confirm that your scalcary models meet the original scheme in your database. Any similarities here can lead to errors during migration or app startup. If you are using the postgrass, make sure the database user is allowed to read/write and migrate tables.
Deployment completely fails:
When the deployment fails, the render usually provides a helper log under the “events” tab. Check there for any mistake messages. Some common criminals include:
A missing
requirements.txt
File or forgotten dependence.A bad
start
Command in render settings. Double check that it indicates your correct entry point (eg,gunicorn app:app
Oruvicorn main:app --host=0.0.0.0 --port=10000
,Inappropriate version. You can explain this in A
runtime.txt
File (eg,python-3.11.1
,
API 500 returns internal server errors:
Internal server errors can be for several reasons. Debug:
Open your render Logs and look for a tracebacks or an unauthorized exception.
Try to reproduce this issue locally using the same request and data.
Add
try/except
Blocks around critical logic to catch mistakes more beautifully and log in.
Even better, compile structural logging or error tracking (for example, with sanitary) to catch them before doing their customers.
The times of a slow response:
If your app is slow or is timely time, check out:
Even if you are still on a free render tier, which is limited to CPU and memory. If you are handling production level traffic, consider upgrading.
If you are running heavy or unexpected database questions, tools like scalchimi
.explain()
Or Jiango Debug toolbar can help.If you often bring the same data, try to catch it using a lightweight memory cache
functools.lru_cache
Or redis example.
Conclusion
The deployment of the Fast API app attached to the postgrade QL on the render is straightforward with the correct structure and setup. Although this guide uses the render for example, concepts are widely applied to the cloud platform.
Through this setup, you can produce, test and deploy strongly manufactured APIS through the Postgrass QL Database.
There are some free levels of free levels on the render, including the postgrass QL database that expires after 90 days until it is upgraded. Consider upgrading to the Better of Production Applications, a planned project for better performance and reliability.
Happy coding!