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 strings both count as invalid. When something's wrong, the response must name the field so the client knows what to fix.
- Register a
POST /usersroute on the existing FastAPIappinstance inmain.py. - Accept a JSON body with two fields:
name(string) andemail(string). - On a valid payload, return HTTP
201with the submitted data as the JSON body:{"name": "...", "email": "..."}. - If
nameis missing or an empty string, return HTTP400with body{"error": "name is required"}. - If
emailis missing or an empty string, return HTTP400with body{"error": "email is required"}. - When both fields are invalid, report
namefirst.
POST /users {"name": "Alice", "email": "alice@example.com"}201 {"name": "Alice", "email": "alice@example.com"}Both fields are present and non-empty — the user is created.
POST /users {"email": "alice@example.com"}400 {"error": "name is required"}name is missing from the payload.
POST /users {"name": "", "email": "alice@example.com"}400 {"error": "name is required"}Empty string is treated the same as missing.
- Use the existing FastAPI
appinstance — 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.
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?
Keep moving through related backend basics problems and build a stronger search-friendly practice loop around this topic.
View track →