Errors and validation
The API never trusts the data it receives. The rules are written once, in the model, and Django REST Framework applies them on every create or update.
Response codes
| Code | When | Example |
|---|---|---|
200 OK | Successful read or update | GET /api/products/ |
201 Created | Successful create | POST /api/products/ |
204 No Content | Successful delete | DELETE /api/products/3/ |
400 Bad Request | Invalid data, or domain name refused | negative price |
404 Not Found | Unknown product or address | GET /api/products/999/ |
405 Method Not Allowed | Method not possible on this address | DELETE /api/products/ |
500 Internal Server Error | Bug, or database unreachable | PostgreSQL stopped |
The format of a validation error
For a 400, DRF returns an object with an array of messages per field:
json
{
"price": ["Ensure this value is greater than or equal to 0."],
"name": ["This field is required."]
}Messages are in English, since LANGUAGE_CODE = 'en-us' in settings.py. The front end does not show these details, only the code: see Talking to the API.
The rules
| Field | Rule | Comes from |
|---|---|---|
name | required, at most 120 characters | CharField(max_length=120) |
description | optional, may be empty | TextField(blank=True) |
price | required, ≥ 0, at most 10 digits including 2 decimals | DecimalField + MinValueValidator(0) |
stock | integer ≥ 0, 0 if missing | PositiveIntegerField(default=0) |
id, created_at, updated_at | ignored if sent | read_only_fields |
The code details: The products API.
In production, no technical details
With DEBUG=False, a 500 error returns a short page, without stack trace or settings. With DEBUG=True (dev), Django shows everything: handy for debugging, dangerous in public.
Never set DEBUG=True in prod
The detailed error page shows paths, SQL queries and part of the configuration. infra/docker-compose.prod.yml sets DEBUG: "False".