GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in FastAPI

SQLi in FastAPI isn't a framework flaw; it's a developer failure. Whether you're using legacy raw drivers or modern ORMs, the injection vector remains the same: treating untrusted input as executable code. To secure a high-performance API, you must decouple the query structure from the data.

The Vulnerable Pattern

from fastapi import FastAPI
import databases

app = FastAPI() database = databases.Database(‘postgresql://user:pass@localhost/db’)

@app.get(‘/items/{item_id}’) async def read_item(item_id: str): # DOOMED: F-string interpolation allows an attacker to escape the quote # Payload: ‘1; DROP TABLE users;—’ query = f”SELECT * FROM items WHERE id = ‘{item_id}’” return await database.fetch_one(query)

The Secure Implementation

The vulnerable snippet uses string formatting to build queries, a classic 'Sink' for SQLi. An attacker can manipulate the query logic by injecting control characters. The secure version leverages SQLAlchemy's abstraction layer. By using the 'where()' clause with a bound parameter, the underlying driver sends the SQL command and the data in separate packets (Prepared Statements). Even if the input contains malicious SQL, the engine treats it as a string literal. Additionally, FastAPI's type hinting (item_id: int) provides a first line of defense by rejecting non-integer payloads before they reach the database logic.

from fastapi import FastAPI, Depends
from sqlalchemy import select
from sqlalchemy.orm import Session

Modern SQLAlchemy 2.0 + FastAPI Dependency Injection

@app.get(‘/items/{item_id}’) def read_item(item_id: int, db: Session = Depends(get_db)): # SECURE: Parameterized query via SQLAlchemy Expression Language # The driver treats item_id as a literal value, not executable SQL stmt = select(Item).where(Item.id == item_id) return db.execute(stmt).scalar_one_or_none()

System Alert • ID: 6982
Target: FastAPI API
Potential Vulnerability

Your FastAPI API might be exposed to SQL Injection (Legacy & Modern)

74% of FastAPI apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.