Ordering backend project · Chapter 10 of 12

Validation and errors

By the end of this chapter you can report every problem in a request at once, send every error the API makes in one shape (with the right status for bad JSON, a broken database rule, a path that does not exist or a bug), keep a 500's real message in the server log instead of the client's screen, and write a strict Pydantic model that refuses a time without its offset or a capacity sent as text. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Ready for production
  • 3 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.

Why you need this

DabbaDrop's app team is wiring the sign-up screen to POST /auth/signup. The design shows a red line under every field that is wrong. Today the API reports one problem at a time, so a new member fixes the email, presses Sign up, and only then learns the password is too short. The app also needs one error shape: it reads error.code and shows error.message, and any answer in another shape breaks the screen.

Bhavna found worse while planning launch week. Here is what chapter 9's code does with what she, or a script with a bug, might send:

$ signup, three bad fields
{"error":{"code":"bad_request","message":"body.email: value is not a valid email address: An email address must have an @-sign."}} [400]
$ login, bad JSON
{"error":{"code":"bad_request","message":"body.10: JSON decode error"}} [400]
$ slot capacity "40"
{"slot":{"id":91,"zone_id":2,"starts_at":"2026-11-03T13:30:00+05:30","ends_at":"2026-11-03T14:00:00+05:30","capacity":40,"status":"open"}} [201]
$ slot with "notes": "extra rider"
{"slot":{"id":92,"zone_id":2,"starts_at":"2026-11-03T15:00:00+05:30","ends_at":"2026-11-03T15:30:00+05:30","capacity":40,"status":"open"}} [201]
$ dishes category chinese
{"error":{"code":"bad_request","message":"query.category: Input should be 'veg', 'jain' or 'non-veg'"}} [400]
$ delete health
{"error":{"code":"http_error","message":"The request ended with 405"}} [405]

Three problems, one reported, written for a developer and not for a screen. A capacity of "40", text, was quietly turned into a number. A notes field Bhavna thought was saved was quietly thrown away. A slot with no offset ("2026-11-03 13:30") did not get in, but only because chapter 6's rules caught it inside the service, after the request was read. None of this is a bug in a service: the input should have been refused at the door, every problem at once, in one shape.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    validation.py: every problem at once

    Write validation_details(errors) in app/core/validation.py. errors is FastAPI's list of problems (exc.errors() of a RequestValidationError), each a dict with "loc", a tuple such as ("body", "items", 0, "quantity"), and "msg". Return one dict per error, in order: {"in": loc[0], "path": the rest of loc joined with "." with every part as text ("items.0.quantity"; "" when there is no rest), "message": msg without the VALUE_ERROR prefix ("Value error, ") that Pydantic puts before an error our own validators raise}.

    The Check turns five errors into details (a missing email, a quantity in a list, a validator's message, a query parameter, a missing body), then runs it on a tiny app of its own: a signup with three bad fields must give the three problems in body email, name and password.

  2. Task 2 · interview question

    Interview: errors.py, one error shape

    Write two functions in app/core/errors.py; error_body (given) builds {"error": {"code", "message"}} with "details" when given. to_error_response(exc) returns (status, body) for any error a request can end with: an AppError gives its status, code, message and details; a RequestValidationError gives 400 bad_json "The request body is not valid JSON" when any of its errors has the type json_invalid, else 422 validation_failed "The request is not valid" with details from validation_details (Task 1); an IntegrityError gives 409 conflict "That already exists" for a unique violation and 409 conflict "Something it refers to does not exist, or still uses it" for a foreign key violation (read pg_code); anything else gives 500 internal "Something went wrong on our side", never the error's own message.

    route_error(method, path, status) is for a request no route matched: 404 not_found "There is no GET /nowhere", 405 method_not_allowed "/health does not take DELETE", and for any other status http_error "The request ended with <status>". install_error_handlers (given) sends every error through the two.

    The Check calls to_error_response on two AppErrors, two RequestValidationErrors, a unique and a foreign key IntegrityError from real inserts and a RuntimeError, calls route_error for a 404 and a 405, then sends a bad signup (422 with three details), a body that is not JSON (400), GET /nowhere (404), DELETE /health (405) and GET /dishes?limit=abc (422, in the query).

    Kunal will ask: why does a 500 say only "Something went wrong on our side", and where does the real error go?

  3. Task 3

    slots/schemas.py: a strict slot

    Make SlotIn in app/modules/slots/schemas.py strict: model_config = ConfigDict(extra="forbid") so a field it does not know is refused; zone_id a StrictInt more than 0; starts_at and ends_at AwareDatetime, so a time without its offset is refused; capacity a StrictInt from 1 to 200.

    The Check validates a good slot, then wants each of these refused, with the problem on the right field: starts_at or ends_at with no offset, capacity "40", 40.5, 0 and 201, zone_id "2" and 0, and an extra field notes. Then a route of its own taking SlotIn must answer 422 for starts_at "2026-11-02 13:30".

What you will learn

  • FastAPI's validation errors: every problem, each with its loc and msg.
  • Details for a client: where (in, path) and what (message), for every problem.
  • Exception handlers: how an error raised anywhere reaches one function that answers it.
  • One error shape for our errors, bad JSON, Postgres's rules, paths that do not exist, and our bugs.
  • Never leaking a 500: the traceback goes to the log, a fixed sentence to the client.
  • Strict models: StrictInt, AwareDatetime, ranges, and extra="forbid".

More in Ready for production

Build "Validation and errors" yourself

DabbaDrop delivers tiffins across Mumbai. You build its ordering API, one module a chapter, and take the whole codebase home. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.