Skip to content

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 ​

CodeWhenExample
200 OKSuccessful read or updateGET /api/products/
201 CreatedSuccessful createPOST /api/products/
204 No ContentSuccessful deleteDELETE /api/products/3/
400 Bad RequestInvalid data, or domain name refusednegative price
404 Not FoundUnknown product or addressGET /api/products/999/
405 Method Not AllowedMethod not possible on this addressDELETE /api/products/
500 Internal Server ErrorBug, or database unreachablePostgreSQL 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 ​

FieldRuleComes from
namerequired, at most 120 charactersCharField(max_length=120)
descriptionoptional, may be emptyTextField(blank=True)
pricerequired, ≥ 0, at most 10 digits including 2 decimalsDecimalField + MinValueValidator(0)
stockinteger ≥ 0, 0 if missingPositiveIntegerField(default=0)
id, created_at, updated_atignored if sentread_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".