External requests remain untrusted even when a Flutter client uses the same DTO class. Validate the wire representation first, then the schema and domain constraints. A safe parser should fail before changing the repository.
Validate in a deliberate sequence
- Check the supported Content-Type.
- Bound the body while reading it, rather than only trusting Content-Length.
- Decode UTF-8 and JSON.
- Require the expected top-level object.
- Validate accepted fields and their types.
- Apply domain constraints before writing.
The task project limits JSON bodies to 16 KiB, requires a non-empty trimmed title and rejects unexpected creation fields. Its title length rule uses Dart String.length, measured in UTF-16 code units; a product needing user-perceived character counts should use an appropriate grapheme-aware policy.
Keep error responses stable
{
"error": {
"code": "invalid_title",
"message": "Title must contain 1–120 characters."
}
}
Clients can make a decision from the code while displaying an appropriate localized message. Use 400 for this sample’s invalid request schema, 415 for an unsupported media type and 413 for an oversized body. Unexpected failures return a generic 500 response without a stack trace or private database details.
Distinguish omission from null
In PATCH, a missing title means leave it unchanged. An explicitly null title is invalid for this non-nullable field. The completion field must be a JSON boolean, not a string containing true. Rejecting unknown writable fields also avoids silently accepting a user-supplied owner or privilege flag.
Test before and after state
Use the supplied handler tests for malformed JSON, invalid UTF-8, excessive input, wrong types and rejected patches. Confirm rejected requests do not modify an existing valid task. Body limits alone do not cover slow request delivery; deployment also needs request deadlines and connection limits.
Exercise
Add an optional due-date field with a documented timestamp policy. Test missing, null, malformed and valid timestamps separately. Keep the typed model, HTTP schema and validation tests aligned instead of adding a non-null assertion in the client.