flawopen.com/Reference/FastAPI SQL Injection

Is FastAPI safe from SQL injection by default?

Python & API Guide
Short answer

FastAPI validates input types with Pydantic, which stops many basic exploits (e.g. ensuring an ID is truly an integer). However, FastAPI does not manage your database connection. If your endpoint constructs SQL with f-strings in SQLAlchemy text() or raw async drivers, it is 100% vulnerable.

Vulnerable vs. Safe FastAPI Pattern

VULNERABLE: F-STRING IN TEXT()
# Pydantic validates that name is a string, but does not sanitize SQL
@app.get("/users")
def get_users(name: str, db: Session = Depends(get_db)):
    query = text(f"SELECT * FROM users WHERE name = '{name}'")
    return db.execute(query).fetchall()
FIXED: PARAMETERIZED TEXT() BINDING
# Colon placeholder binds value at protocol level
@app.get("/users")
def get_users(name: str, db: Session = Depends(get_db)):
    query = text("SELECT * FROM users WHERE name = :name")
    return db.execute(query, {"name": name}).fetchall()

Prevention Checklist