Validation and data

Write parameterized queries

Keep SQL structure separate from untrusted values and translate database outcomes into API responses.

8 minute lesson

~~~

Never build SQL by concatenating request values. Quoting by hand is not a reliable security boundary.

Write the SQL structure with placeholders and bind the values through the database library. Handle expected constraint errors explicitly, and let unexpected errors reach centralized logging rather than returning raw database messages.

INSERT INTO books (id, title, author, published_year, created_at)
VALUES (?, ?, ?, ?, ?)

Parameters protect value positions. They cannot safely stand in for SQL identifiers or keywords such as a column name or sort direction. If a client can choose sorting, map a small allowlist of API values to fixed SQL fragments rather than interpolating the raw query string.

Translate expected database outcomes at the repository boundary. A uniqueness or check violation can become a documented conflict or validation problem; a missing row becomes 404; an unexpected I/O or programming error remains an internal failure. Log the error class and request ID, not the full SQL plus bound personal values. Test a title containing quotes and SQL-looking text—the value should be stored literally and the table must remain intact.

Replace the in-memory create and detail operations with prepared parameterized statements.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →