Skip to main content
EasyBackendBuild

Validate Request Payloads

Add a `POST /users` route to the FastAPI app in `main.py`. The route accepts a JSON body and creates a new user — but only if the payload is valid. Every field must be present and non-empty. Missing fields and empty str...

What you will practice

PythonREST APIs / RoutesError HandlingValidationPydantic

Requirements

  • Register a `POST /users` route on the existing FastAPI `app` instance in `main.py`.
  • Accept a JSON body with two fields: `name` (string) and `email` (string).
  • On a valid payload, return HTTP `201` with the submitted data as the JSON body: `{"name": "...", "email": "..."}`.
  • If `name` is missing or an empty string, return HTTP `400` with body `{"error": "name is required"}`.
  • If `email` is missing or an empty string, return HTTP `400` with body `{"error": "email is required"}`.
  • When both fields are invalid, report `name` first.

Starter files

main.pyEditable starter

What the judge checks

  • Runs in the python environment with the python-pytest runner.
  • Uses a 5000ms judge budget.
  • Behavior rules include: Valid Payload Returns 201, Missing Name Returns 400, Missing Email Returns 400, Empty String Treated As Missing.

Constraints

  • Use the existing FastAPI `app` instance — do not create a new one.
  • The 400 error body must be `{"error": "<field_name> is required"}` — not Pydantic's default 422 format.
  • Do not store or persist the user data — just validate and echo it back.

Example behavior

Input
POST /users  {"name": "Alice", "email": "alice@example.com"}
Output
201  {"name": "Alice", "email": "alice@example.com"}

Both fields are present and non-empty — the user is created.

Input
POST /users  {"email": "alice@example.com"}
Output
400  {"error": "name is required"}

name is missing from the payload.

Follow-up

This validates two required fields. Real APIs often validate dozens — format constraints, uniqueness checks, cross-field rules. How would you structure validation so adding a new rule is one line, not scattered conditionals?