DevPath
Foundation lesson · 12 min

Validate payloads and protect SQL

Check shape at the edge and bind values in queries.

Report specific errors

Validate that a payload is an object before reading fields. Distinguish a missing quantity from a quantity with the wrong type, and reject bool when an integer is required because bool is an int subclass in Python. Return field-level messages while keeping internal details out of the response.

Bind, do not interpolate

Never insert a user's value into SQL text with an f-string or concatenation. Pass it as a parameter through the database driver's binding mechanism. Parameters protect values, not SQL identifiers; a requested sort column needs an explicit allowlist.

allowed_sort = {'created_at', 'title'}
if sort not in allowed_sort:
    raise ValueError('invalid sort')
cursor.execute('SELECT * FROM jobs WHERE owner_id = ?', (owner_id,))

Test the boundary

Test missing fields, wrong types, an empty string, and a string containing SQL punctuation. Assert that the punctuation is treated as data and cannot change the query's meaning. Also test authorization after validation: a well-formed owner ID should not permit access to another user's row.

Check your understanding

Can a bound parameter safely replace a requested SQL column name?

Show explanation

No. Parameters bind values. Choose identifiers from a fixed allowlist before building SQL syntax.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Validate a request payload with specific errors

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.