- Python 3.10+
- MySQL Server running locally
-
Create Virtual Environment
python -m venv venv -
Activate Virtual Environment
.\venv\Scripts\activate
-
Install Dependencies
pip install -r requirements.txt -
Database Configuration Ensure your MySQL server is running and you have created a database named
py_db. Updateapp/database.pywith your MySQL credentials (username/password).
Run the server using uvicorn:
uvicorn app.main:app --reload --port 8001The API will be available at http://127.0.0.1:8001.
- POST /signin: Login with email/password to get an access token.
- POST /signup: Register a new user.
For a Python FastAPI application, you have several excellent choices:
-
SQLite (Best for Development)
- Why: Zero configuration, valid SQL, built into Python. Stores data in a local file.
- Use Case: Local development, testing, small prototypes.
-
PostgreSQL (Best for Production)
- Why: The industry standard for open-source relational databases. Powerful, robust features (JSON support, concurrency).
- Use Case: Production applications, complex data requirements.
-
MySQL (Popular Alternative)
- Why: Extremely popular, powering much of the web. simple to set up, widely supported by hosting providers.
- Use Case: If you have legacy systems, existing MySQL infrastructure, or specific team preference.
We use SQLAlchemy for database connections. It abstracts the underlying SQL, allowing you to switch databases by changing just one line of configuration.
Core SQLAlchemy:
pip install sqlalchemyDatabase Drivers (Install the one you need):
- For SQLite: No install needed (built-in).
- For PostgreSQL:
pip install psycopg2-binary
- For MySQL:
(Note: We recommend
pip install pymysql
pymysqlfor easiest installation on Windows/Mac/Linux)
Create a file named database.py to handle the connection.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# --- DATABASE CONFIGURATION ---
# Uncomment the line for the database you are using
# 1. SQLite (Default for Dev)
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# 2. PostgreSQL
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/dbname"
# 3. MySQL
# SQLALCHEMY_DATABASE_URL = "mysql+pymysql://user:password@localhost/dbname"
# Check for SQLite specific argument
connect_args = {}
if "sqlite" in SQLALCHEMY_DATABASE_URL:
connect_args = {"check_same_thread": False}
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args=connect_args
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()Define your database tables as Python classes.
from sqlalchemy import Boolean, Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)Dependency to get the DB session.
from sqlalchemy.orm import Session
from fastapi import Depends, FastAPI, HTTPException
from . import models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/")
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
# ... use db to create user ...
pass