FlawOpen

flawopen.com/Reference/FastAPI SQL Injection

Does FastAPI prevent SQL Injection by default?

Python & API Guide
The short answer

Pydantic checks whether a value matches the declared input type; it does not rewrite SQL or turn a Python string into a database parameter. A validated name: str is still caller-controlled text. Think of validation as checking the label on a parcel: it confirms what kind of value arrived, while parameter binding seals the value outside the SQL instruction sheet. Keep the SQL template fixed and pass values separately through SQLAlchemy.

Vulnerable vs. safe FastAPI pattern

VULNERABLE: interpolation changes SQL text
# A string type check does not make input safe inside SQL syntax
@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()
SAFE: SQLAlchemy binds the value separately
# :name is a bind parameter; the value is passed separately
@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()

What parameter binding does not cover

A bound parameter represents a data value, not a table name, column name, SQL operator, or sort direction. If a request must choose a sort field, map the choice to a fixed allow-list of SQLAlchemy column expressions; never splice the raw request string into SQL. Parameterization also does not replace authorization: constrain which rows the caller may read, and use a database account with only the privileges the endpoint needs.

Prevention checklist

References

See also SQL Injection (CWE-89): How It Works and How to Prevent It in Every Language — flawopen.com GORM Raw SQL: Prevent SQL Injection in Go Is Escaping Quotes Enough to Prevent SQL Injection? Is Using an ORM Enough to Prevent SQL Injection? Is Knex.js Safe from SQL Injection? MyBatis ${} vs #{}: Prevent SQL Injection MySQLi vs PDO: Secure Prepared Statements