Skip to main content
Problem 24

Validate Request Payloads

EASYBUILD
REST APIs / Routes+3

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.

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.
Examples
Example 1
Input
POST /users  {"name": "Alice", "email": "alice@example.com"}
Output
201  {"name": "Alice", "email": "alice@example.com"}
Note

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

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

name is missing from the payload.

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

Empty string is treated the same 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.
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?

Hints
Related Practice
Track
Backend Basics

Keep moving through related backend basics problems and build a stronger search-friendly practice loop around this topic.

View track →
Console output will appear here...