Fix SQL Injection (Legacy & Modern) in Falcon
Falcon's bare-bones design means the framework won't save you from your own bad habits. Without a built-in ORM, developers often resort to raw SQL execution. If you are using f-strings, format(), or % to build queries, you have a critical SQL Injection (SQLi) vulnerability. This guide demonstrates how to move from dangerous string interpolation to secure parameterized queries and modern ORM integration.
The Vulnerable Pattern
import falcon
import sqlite3
class UserResource:
def on_get(self, req, resp):
# VULNERABLE: Direct string interpolation from user input
user_id = req.get_param(‘id’)
conn = sqlite3.connect(‘app.db’)
cursor = conn.cursor()
# Attacker can pass: 1' OR '1'='1
query = f"SELECT username, email FROM users WHERE id = '{user_id}'"
cursor.execute(query)
result = cursor.fetchone()
resp.media = {'user': result}</code></pre>
The Secure Implementation
The vulnerability exists because f-strings and string concatenation merge 'commands' (SQL) with 'data' (user input) before the database sees them. An attacker can break the syntax and inject their own logic. The fix is 'Parameterized Queries'. By passing parameters separately from the query string, the database driver ensures the input is treated strictly as data. In modern Falcon apps, using an abstraction layer like SQLAlchemy with 'text()' and bindparams provides a robust defense while keeping code clean. Never trust 'req.get_param' or 'req.media' values inside a raw string.
import falcon
import sqlite3
from sqlalchemy import create_engine, text
OPTION 1: Parameterized Query (Legacy/Direct)
class SecureResource:
def on_get(self, req, resp):
user_id = req.get_param(‘id’)
conn = sqlite3.connect(‘app.db’)
cursor = conn.cursor()
# The ’?’ is a placeholder; the driver handles escaping
cursor.execute(“SELECT username, email FROM users WHERE id = ?”, (user_id,))
resp.media = {‘user’: cursor.fetchone()}
OPTION 2: Modern (SQLAlchemy Core)
class ModernResource:
def init(self, engine):
self.engine = engine
def on_get(self, req, resp):
user_id = req.get_param('id')
with self.engine.connect() as conn:
# Using bind parameters
stmt = text("SELECT username, email FROM users WHERE id = :id")
result = conn.execute(stmt, {"id": user_id}).fetchone()
resp.media = {'user': dict(result) if result else None}</code></pre>
Your Falcon API
might be exposed to SQL Injection (Legacy & Modern)
74% of Falcon apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.