8. Validation and error models
This file supports the Week 2 segment on error model and validation design.
Goals for this segment
Design a consistent error format for the Snippets API.
Decide which validations to enforce and where (middleware vs per-endpoint).
Make sure the design is reflected in both:
Your Express implementation.
Your OpenAPI specification.
Error format
Recommend something simple such as:
{ "error": "Human-readable message" }or
{
"error": {
"code": "SNIPPET_NOT_FOUND",
"message": "Snippet with id 42 was not found"
}
}The exact format is less important than being consistent across endpoints.
Validation examples
For the Snippets API, talk through validations like:
POST /api/snippetstitleis required and non-empty.contentsis required and non-empty.Optional fields like
is_privatehave sensible defaults.
PUT /api/snippets/:idReject updates with empty
titleorcontents.Return
404wheniddoes not exist.
Any
/:idrouteValidate that
idis a number before hitting the database.
Connect these decisions back to status codes from Week 1:
400 Bad Requestfor invalid inputs.404 Not Foundwhen a resource is missing.500 Internal Server Errorfor unexpected issues.
Last updated