APIs · Intermediate · 20 min
Add filtering and sorting to an API without opening an injection hole
By Padding · Updated 18 Nov 2026
Python 3.15 · FastAPI 0.165 · SQLite
You will turn a products endpoint into one that accepts status, price, search and sort parameters, and prove that the injection attacks which break a naive version are rejected by yours.
On this page
A list endpoint rarely stays a plain list. Someone asks for "only active products", then "nothing under 5,000", then "search by name", then "cheapest first". Each request turns into a piece of SQL, and the quickest way to add a piece of SQL is to paste the query string value into it. That is how injection gets into code written by people who already know about injection: the login form was done properly, but the filter on the catalogue was added on a Friday.
In this tutorial you build a small shop API in FastAPI with four query parameters: ?status=, ?min_price=, ?q= and ?sort=-price. You first write the naive version and break it with three classic attacks. Then you rebuild it in layers: a query parameter model that validates every value, a WHERE clause made only of placeholders, and an allowlist for sort fields, because ORDER BY cannot take a bound parameter. Finally you replay the attacks against the safe version and lock the results into tests.
The fundamentals of parameterised queries are in prevent SQL injection in Python and Node.js. This tutorial applies them to the part of an API where they most often slip.
Step 1 · Create the project and a database to attack
Make a throwaway project folder and add FastAPI with its standard extras, which bring the fastapi command and the Uvicorn server. The version range allows patch releases of 0.165 only:
mkdir -p ~/shop-api-demo
cd ~/shop-api-demo
uv init --no-package
uv add "fastapi[standard]>=0.165,<0.166"The API reads from SQLite, which ships with Python and needs no server. The seed script creates a products table with one product that is not published yet, and a staff table that the products endpoint should never reveal anything about. Prices are whole naira, stored as integers so there is no floating-point rounding:
cat > seed.py <<'PY'
import sqlite3
con = sqlite3.connect("shop.db")
con.executescript("""
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS staff;
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
status TEXT NOT NULL,
price INTEGER NOT NULL,
published INTEGER NOT NULL
);
CREATE TABLE staff (
email TEXT PRIMARY KEY,
password_hash TEXT NOT NULL
);
""")
con.executemany(
"INSERT INTO products (name, status, price, published) VALUES (?, ?, ?, ?)",
[
("Solar lantern", "active", 18500, 1),
("Power bank 20000mAh", "active", 24000, 1),
("USB-C charger", "active", 6500, 1),
("Feature phone", "discontinued", 15000, 1),
("100% cotton tote", "active", 4000, 1),
("Unreleased tablet", "active", 99000, 0),
],
)
con.execute(
"INSERT INTO staff VALUES (?, ?)",
("admin@example.com", "$argon2id$v=19$m=65536$demo-hash"),
)
con.commit()
con.close()
print("Seeded 6 products and 1 staff account")
PY
uv run python seed.pyAdd a small helper that prints only the product names from a JSON response, so the results of each request fit on one line. It prints error bodies unchanged:
cat > show.py <<'PY'
import json
import sys
data = json.load(sys.stdin)
if isinstance(data, list):
print(" | ".join(product["name"] for product in data) or "(no products)")
else:
print(json.dumps(data))
PYCheck it worked
The seed script printed Seeded 6 products and 1 staff account. Confirm the installed versions:
uv run python -c "import fastapi, pydantic; print(fastapi.__version__, pydantic.VERSION)"The output is something like 0.165.0 2.14.4. The first number is the FastAPI version you pinned; the second is whichever pydantic release uv chose as the newest that FastAPI allows, so it may differ.
Step 2 · Write the naive endpoint and break it
This is the version that gets written under time pressure. Every filter is an f-string, and the sort value goes straight after ORDER BY. Save it as naive.py. You delete it at the end; never deploy it:
cat > naive.py <<'PY'
import sqlite3
from fastapi import FastAPI
app = FastAPI(title="Shop API (naive, do not deploy)")
@app.get("/products")
def list_products(status: str | None = None, q: str | None = None, sort: str = "name"):
sql = "SELECT id, name, status, price FROM products WHERE published = 1"
if status:
sql += f" AND status = '{status}'"
if q:
sql += f" AND name LIKE '%{q}%'"
sql += f" ORDER BY {sort}"
con = sqlite3.connect("shop.db")
con.row_factory = sqlite3.Row
rows = [dict(row) for row in con.execute(sql)]
con.close()
return rows
PYStart it on port 8001 in your second terminal. fastapi dev listens on your own computer only, which is where this file belongs:
cd ~/shop-api-demo
uv run fastapi dev naive.py --port 8001Back in the first terminal, make an honest request. -G with --data-urlencode builds the query string and encodes spaces and quotes for you:
cd ~/shop-api-demo
curl -s -G --data-urlencode "status=active" http://127.0.0.1:8001/products | uv run python show.pyThe output is the four active, published products: 100% cotton tote | Power bank 20000mAh | Solar lantern | USB-C charger.
Attack 1: break out of the quotes. The value closes the string literal and adds a condition that is always true. Because AND binds tighter than OR, the published = 1 check no longer applies to every row:
curl -s -G --data-urlencode "status=active' OR '1'='1" http://127.0.0.1:8001/products | uv run python show.pyThe list now ends with Unreleased tablet, a product nobody outside the company should see yet.
Attack 2: use the sort order as a yes/no oracle. The sort value is SQL, so it can contain a subquery. This one asks "is the first character of the admin's password hash code 36, a $?". If yes, the list is sorted cheapest first; if no, most expensive first. Run it twice, with 36 and with 35:
curl -s -G --data-urlencode 'sort=CASE WHEN (SELECT unicode(password_hash) FROM staff)=36 THEN price ELSE -price END' http://127.0.0.1:8001/products | uv run python show.py
curl -s -G --data-urlencode 'sort=CASE WHEN (SELECT unicode(password_hash) FROM staff)=35 THEN price ELSE -price END' http://127.0.0.1:8001/products | uv run python show.pyThe first list starts with 100% cotton tote, the cheapest. The second starts with Power bank 20000mAh, the dearest. The response never contains the hash, yet the order answers the question. A script that asks one question per character reads the whole hash, or any other value in the database.
Attack 3: widen a search with wildcards. No quotes are needed for this one. % and _ are LIKE wildcards, so q=_ (any one character) matches every name:
curl -s -G --data-urlencode "q=_" http://127.0.0.1:8001/products | uv run python show.pyAll five published products come back. On its own that is a nuisance, but on a large table a pattern like %a%b%c%d% makes the database work hard for every request.
Check it worked
You saw Unreleased tablet in the output of attack 1, and the two oracle requests started with different products. Stop the naive server with Ctrl+C in the second terminal.
Step 3 · Describe the allowed filters as a model
The first layer decides what a valid request looks like before any SQL exists. FastAPI can read all query parameters into one Pydantic model. Put it in its own file:
cat > filters.py <<'PY'
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
class ProductFilters(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
status: Literal["active", "discontinued"] | None = None
min_price: Annotated[int, Field(ge=0, le=10_000_000)] | None = None
q: Annotated[str, Field(min_length=1, max_length=50)] | None = None
sort: Annotated[str, Field(min_length=1, max_length=40)] = "name"
limit: Annotated[int, Field(ge=1, le=50)] = 20
PYWhat each line rules out:
statusis aLiteral, so only the two real statuses pass. A string that closes a quote is not one of them.min_pricemust parse as a whole number from 0 to ten million.0 OR 1=1is not a number.qis free text, so validation cannot make it safe. It only bounds the length. The next step handles it.sortis also free text for now, capped at 40 characters. The allowlist in a later step decides what it may say.limitstops anyone asking for the whole table in one request.extra="forbid"rejects parameters you did not define, so a typo such as?sort_by=pricegets an error instead of being silently ignored.
Check it worked
uv run python -c 'from filters import ProductFilters; print(ProductFilters(min_price="5000", sort="-price"))'
uv run python -c 'from pydantic import ValidationError
from filters import ProductFilters
try:
ProductFilters(status="sold")
except ValidationError as err:
print("rejected:", err.errors()[0]["msg"])'The first line prints status=None min_price=5000 q=None sort='-price' limit=20: the text "5000" from a URL became the integer 5000. The second prints rejected: Input should be 'active' or 'discontinued'.
Step 4 · Build the WHERE clause from placeholders only
The second layer keeps values out of the SQL text. Each filter adds a fixed fragment that you wrote, with a ? where the value goes, and the value goes into a separate list. The database receives the two apart and never reads a value as SQL.
The search is the one case where a bound value still needs work. LIKE treats % and _ inside the value as wildcards, as attack 3 showed. escape_like puts a backslash in front of each, and ESCAPE '\' tells SQLite that a backslash means "the next character is literal":
cat > queries.py <<'PY'
from filters import ProductFilters
def escape_like(text: str) -> str:
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
def build_where(filters: ProductFilters) -> tuple[str, list]:
clauses = ["published = 1"]
params: list = []
if filters.status is not None:
clauses.append("status = ?")
params.append(filters.status)
if filters.min_price is not None:
clauses.append("price >= ?")
params.append(filters.min_price)
if filters.q is not None:
clauses.append("name LIKE ? ESCAPE '\\'")
params.append(f"%{escape_like(filters.q)}%")
return " AND ".join(clauses), params
PYpublished = 1 is always the first clause, so no combination of filters can reach unpublished rows. If you later move to PostgreSQL, only the placeholder style changes (%s in psycopg, $1 in node-postgres). The shape of the function stays.
A note on search in more than one language: SQLite's built-in LIKE ignores case for ASCII letters only. q=lantern finds Solar lantern, but a search for ọja will not match Ọja in a Yoruba product name. If your catalogue has names in Yoruba, Hausa, Amharic or French, normalise case in Python before storing a search column, or use a database whose collation handles Unicode, and test it with real names.
Check it worked
uv run python -c 'from filters import ProductFilters; from queries import build_where; print(build_where(ProductFilters(status="active", q="100%")))'The output is:
("published = 1 AND status = ? AND name LIKE ? ESCAPE '\\'", ['active', '%100\\%%'])The SQL text contains no user input at all. Python shows each backslash doubled, so the search value is really %100\%%: wildcards around a literal 100%.
Step 5 · Allowlist the sort fields
The third layer handles ORDER BY. Placeholders stand for values, and a column name is not a value. If you bind the sort field, the database sorts by the constant text 'price', which is the same for every row, so nothing is sorted and nothing fails. See it for yourself:
uv run python -c 'import sqlite3; con = sqlite3.connect("shop.db"); print([r[0] for r in con.execute("SELECT name FROM products WHERE published = 1 ORDER BY ?", ["price"])])'The names come back in the order they were inserted, starting with Solar lantern at 18,500, not the cheapest. No error tells you the sort was ignored.
So the sort value must become SQL, and the only safe way to do that is to map it through a table you wrote. The client sends public names; your code looks each one up and uses your text, never theirs:
cat > sorting.py <<'PY'
SORTABLE = {"name": "name", "price": "price", "newest": "id"}
MAX_SORT_FIELDS = 2
class SortError(ValueError):
pass
def build_order_by(sort: str) -> str:
keys = [key.strip() for key in sort.split(",")]
if len(keys) > MAX_SORT_FIELDS:
raise SortError(f"Sort by at most {MAX_SORT_FIELDS} fields.")
parts: list[str] = []
seen: set[str] = set()
for key in keys:
name = key.removeprefix("-")
if name not in SORTABLE:
allowed = ", ".join(sorted(SORTABLE))
raise SortError(f"Unknown sort field. Use one of: {allowed}. Put - in front for descending.")
if name in seen:
raise SortError(f"'{name}' is listed twice in sort.")
seen.add(name)
direction = "DESC" if key.startswith("-") else "ASC"
parts.append(f"{SORTABLE[name]} {direction}")
if "newest" not in seen:
parts.append("id ASC")
return ", ".join(parts)
PYDetails worth keeping when you adapt this:
- The public name and the column can differ (
newestmaps toid). That lets you rename a column without breaking clients, and it means a client never learns your column names from the API. - The direction comes from your two strings,
ASCandDESC, chosen by a-prefix. The client's text never reaches the SQL. - The error message lists the allowed fields but does not repeat the client's input back.
id ASCat the end breaks ties, so two products with the same price always come back in the same order. Pagination depends on that.
Check it worked
uv run python -c 'from sorting import build_order_by; print(build_order_by("-price")); print(build_order_by("price,-name"))'
uv run python -c 'from sorting import SortError, build_order_by
try:
build_order_by("price; DROP TABLE products")
except SortError as err:
print("rejected:", err)'The output is price DESC, id ASC, then price ASC, name DESC, id ASC, then rejected: Unknown sort field. Use one of: name, newest, price. Put - in front for descending.
Step 6 · Wire the safe endpoint
main.py joins the three layers. Annotated[ProductFilters, Query()] tells FastAPI to fill the model from the query string, and a SortError becomes 400 Bad Request with its message. The f-string that assembles the statement only joins fragments that came from your own code: the clauses from build_where and the columns from SORTABLE. Every client value, including limit, travels in the parameter list:
cat > main.py <<'PY'
import sqlite3
from contextlib import closing
from typing import Annotated
from fastapi import FastAPI, HTTPException, Query
from filters import ProductFilters
from queries import build_where
from sorting import SortError, build_order_by
app = FastAPI(title="Shop API")
@app.get("/products")
def list_products(filters: Annotated[ProductFilters, Query()]):
try:
order_by = build_order_by(filters.sort)
except SortError as err:
raise HTTPException(status_code=400, detail=str(err))
where, params = build_where(filters)
sql = (
"SELECT id, name, status, price FROM products"
f" WHERE {where} ORDER BY {order_by} LIMIT ?"
)
with closing(sqlite3.connect("file:shop.db?mode=ro", uri=True)) as con:
con.row_factory = sqlite3.Row
rows = con.execute(sql, [*params, filters.limit]).fetchall()
return [dict(row) for row in rows]
PYThe connection opens the database read-only (mode=ro). A list endpoint has no reason to write, so even a mistake added later cannot change data through it. On PostgreSQL or MySQL the same idea is a database user with SELECT rights only.
Start it on port 8000 in the second terminal:
uv run fastapi dev main.pyCheck it worked
Combine all four filters the way a shop page would:
curl -s -G --data-urlencode "status=active" --data-urlencode "min_price=5000" --data-urlencode "sort=-price" http://127.0.0.1:8000/products | uv run python show.py
curl -s -G --data-urlencode "q=100%" http://127.0.0.1:8000/products | uv run python show.pyThe first prints Power bank 20000mAh | Solar lantern | USB-C charger: active, at least 5,000, dearest first. The second prints only 100% cotton tote, because % in the search is now a plain character.
Step 7 · Replay the attacks against the safe version
Send the same three attacks to port 8000, plus two that target the new layers. -w adds the status code on its own line:
curl -s -w '\n%{http_code}\n' -G --data-urlencode "status=active' OR '1'='1" http://127.0.0.1:8000/products
curl -s -w '\n%{http_code}\n' -G --data-urlencode 'sort=CASE WHEN (SELECT unicode(password_hash) FROM staff)=36 THEN price ELSE -price END' http://127.0.0.1:8000/products
curl -s -G --data-urlencode "q=_" http://127.0.0.1:8000/products | uv run python show.py
curl -s -w '\n%{http_code}\n' -G --data-urlencode "sort=-published" http://127.0.0.1:8000/products
curl -s -w '\n%{http_code}\n' -G --data-urlencode "sort_by=price" http://127.0.0.1:8000/productsWhat you get back:
- The quote break-out is
422. Thedetailnames["query","status"]with"type":"literal_error": the value is not one of the allowed statuses, so it never reaches the database. - The sort oracle is
422with"type":"string_too_long". It is longer than 40 characters, and even a shorter one would fail the allowlist. - The wildcard search prints
(no products). No name contains a literal underscore. sort=-publishedis a real column, but not a public one, so it is400with{"detail":"Unknown sort field. Use one of: name, newest, price. Put - in front for descending."}. A client can read that and fix its request.- The misspelt
sort_byis422with"type":"extra_forbidden".
There are two codes because they come from different layers. FastAPI answers 422 when the request does not fit the model. Your code answers 400 when the request fits but asks for something the API does not offer. Pick one convention for your API, write it in the API docs, and keep it.
Check it worked
None of the five responses contains Unreleased tablet or anything from the staff table, and none is a 500. A 500 on an attack string means the input reached the database and broke the query, so treat one as a bug even when no data leaks.
Step 8 · Lock it in with tests
The attacks you typed make good test cases. If someone later adds a filter with an f-string, a test fails before the change ships. Add pytest and httpx, which FastAPI's TestClient needs, as development dependencies:
uv add --dev "pytest>=9.2,<9.3" "httpx>=0.28,<0.29"
mkdir -p tests
cat > tests/test_products.py <<'PY'
import pytest
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def names(response):
return [product["name"] for product in response.json()]
def test_filters_and_sort_work_together():
response = client.get("/products", params={"status": "active", "min_price": 5000, "sort": "-price"})
assert response.status_code == 200
assert names(response) == ["Power bank 20000mAh", "Solar lantern", "USB-C charger"]
def test_search_treats_wildcards_as_text():
assert names(client.get("/products", params={"q": "100%"})) == ["100% cotton tote"]
assert names(client.get("/products", params={"q": "_"})) == []
@pytest.mark.parametrize(
"params",
[
{"status": "active' OR '1'='1"},
{"status": "x'; DROP TABLE products; --"},
{"q": "' OR 1=1 --"},
{"sort": "CASE WHEN (SELECT 1 FROM staff) THEN price END"},
{"sort": "price; DROP TABLE products"},
{"sort": "-published"},
{"min_price": "0 OR 1=1"},
{"sort_by": "price"},
],
)
def test_attacks_never_reach_hidden_rows(params):
response = client.get("/products", params=params)
assert response.status_code in (200, 400, 422)
assert "Unreleased tablet" not in response.text
def test_unknown_sort_field_is_a_clear_400():
response = client.get("/products", params={"sort": "cost"})
assert response.status_code == 400
assert "Use one of: name, newest, price" in response.json()["detail"]
PYThe tests read the shop.db you seeded in the first step. TestClient calls the app in-process, so the server does not need to be running for them.
Check it worked
uv run python -m pytest -qThe output ends with 11 passed: eight of them from the parametrised attack list. To see the tests earn their place, break the search filter, which is the only free-text value that reaches the WHERE clause. In queries.py, replace the two lines under if filters.q is not None: with clauses.append(f"name LIKE '%{filters.q}%'") and run the tests again. test_search_treats_wildcards_as_text fails, and so does the ' OR 1=1 -- attack case. Then change it back. The same trick on status would prove nothing: its Literal type rejects every attack with a 422 before any SQL is built.
Step 9 · Stop the server and clean up
Press Ctrl+C in the second terminal. The project folder holds only what you made here, including the naive file, so delete all of it:
cd ~
rm -rf ~/shop-api-demoTo apply this to your own API, search it for SQL next to an f-string, + or .format(, and check every ORDER BY for a value that came from a request.
Next steps
- Go back to the fundamentals and the other places parameters cannot reach: prevent SQL injection in Python and Node.js.
- Page through long result sets without offsets that drift: paginate API results with cursors. The
idtie-breaker from this tutorial is what makes a cursor stable. - Send and debug requests like the ones above: test an API with curl.
Part of these paths
Related tutorials
- How to Prevent SQL Injection in Python and Node.jsYou will write a login lookup that an attacker can break with one line of input, watch it fail, fix it with parameterised queries in both Python and Node.js, and learn the cases where parameters are not enough.
- Paginate API results with cursors instead of offsetsYou will replace offset pagination in a FastAPI orders endpoint with keyset pagination behind an opaque cursor, so that 100,000 rows page quickly and stay in order while new rows arrive.
- How to Build a REST API with FastAPIYou will build a small items API with FastAPI 0.163 on Python 3.15 that validates its input, returns the right HTTP status codes, never shows a stack trace to callers, documents itself, and has automated tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials