Backend - thesairam/backend GitHub Wiki
This backend powers a simple product selling website using:
-
FastAPI — high-performance Python web framework
-
Uvicorn — ASGI server to run the app
-
SQLModel — modern ORM combining SQLAlchemy + Pydantic
-
PostgreSQL — as the database
-
psycopg2-binary — PostgreSQL database adapter
-
python-dotenv — to manage environment variables
bashCopyEditproduct_site/ └── backend/ ├── env/ # Python virtual environment ├── .env # Environment variables ├── main.py # FastAPI application └── models.py # SQLModel models
Create the project directories:
bashCopyEditmkdir -p product_site/backend cd product_site/backend
Create a Python virtual environment:
bashCopyEditpython3 -m venv env source env/bin/activate
Install required dependencies via pip:
phpCopyEditpip install fastapi uvicorn sqlmodel psycopg2-binary python-multipart python-dotenv
Create a .env
file to store your database connection string:
bashCopyEditDATABASE_URL=postgresql+psycopg2://shop_admin:secure_password@localhost/product_store
Access PostgreSQL:
nginxCopyEditsudo -u postgres psql
Inside the prompt:
pgsqlCopyEditCREATE USER shop_admin WITH PASSWORD 'secure_password'; CREATE DATABASE product_store OWNER shop_admin; GRANT ALL PRIVILEGES ON DATABASE product_store TO shop_admin; \q
Example product
table structure:
Check table structure:
nginxCopyEditsudo -u postgres psql product_store \d product;
models.py
— defines the Product model using SQLModel.
main.py
— contains FastAPI app, routes, and database session management.
A Session is a temporary connection to the database that lets you:
-
Perform SQL queries
-
Add, delete, or update records
-
Control transactions
Each API route gets its own session. Sessions must be opened, used, and closed properly to avoid database connection issues.
Use Uvicorn to serve the FastAPI app:
cssCopyEdituvicorn main:app --reload
Open:
arduinoCopyEdithttp://127.0.0.1:8000/docs
Use Swagger UI to test:
-
GET /products/
— List all products -
POST /products/
— Add a product
-
FastAPI + Uvicorn set up for backend API
-
SQLModel integrated with PostgreSQL via psycopg2
-
Database connection string secured using
.env
-
PostgreSQL database and product table configured
-
API endpoints operational and testable via Swagger UI
-
Add
.env
to.gitignore
to avoid exposing credentials. -
Use
--reload
flag with Uvicorn during development only. -
Swagger UI is automatically generated at
/docs
. -
SQLModel uses Pydantic models for validation and SQLAlchemy ORM under the hood.