Start learning free

LESSON 15 OF 56 · SECURITY: INJECTION

SQL Injection: Values, Not Code in Python

Practice

The shop's GET /search?q= finds a customer by their exact name. A first version built the SQL with an f-string that pasted q between two quotes after WHERE name =, so whatever the visitor typed became part of the SQL itself. This hole is called SQL injection.

What an attacker gets: sending q=' OR '1'='1 makes the WHERE true for every row, so one request returns every customer's name and email. Sending q=' UNION SELECT service, secret FROM api_keys -- adds the rows of another table and reads the shop's secret API keys. Even an honest search for Liam O'Brien crashed, because the apostrophe ended the quoted name early.

The fix is a placeholder. Write ? in the SQL where a value goes, and pass the values separately, as a tuple, in the second argument of db.execute. The database reads the SQL first and then fills in each value as plain data, so quotes and SQL words inside it are just characters. Each ? takes the next value in order, and a tuple of one value still needs its comma, like (name,).

category = request.args.get("category", "")
rows = db.execute(
    "SELECT name, price FROM products WHERE category = ? AND price < ?",
    (category, 20),
).fetchall()

With placeholders, both attacks become plain names that no customer has, so they find nothing. The requests and answers your code must give:

GET /search?q=Ana Pop  →  200  [{"email": "ana@example.com", "name": "Ana Pop"}]
GET /search?q=Liam O'Brien  →  200  [{"email": "liam@example.com", "name": "Liam O'Brien"}]
GET /search?q=' OR '1'='1  →  200  []
GET /search?q=' UNION SELECT service, secret FROM api_keys --  →  200  []
GET /search?q=Ana  →  200  []

The last line shows that = compares the whole name: Ana is not Ana Pop.

Your task: the starting code reads q and turns rows into a list of dicts, but the query is missing, so every request answers 500 for now. Below q, build query from two string pieces: a SELECT of name and email from customers, and a WHERE that compares name with a ?. Then run it with (q,) as its values and keep .fetchall() in rows.


Assignment
Follow the Coding Tutorial to write the search query with a ? placeholder and run it with q passed as a separate value.


Hint
Never put q inside the SQL text: no f-string, no +, no .format. Write the ? without quotes around it, end each string piece with a space so the words stay apart, and keep the comma in (q,).


STEP 1 OF 4
    Ctrl + Enter to check

    Secx Sql Injection in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free