Get AI summaries of any video or article — Sign up free
Post Request in FastAPI | What is Request Body? | Video 5 | CampusX thumbnail

Post Request in FastAPI | What is Request Body? | Video 5 | CampusX

CampusX·
5 min read

Based on CampusX's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.

TL;DR

Use app.post for the create endpoint because the client sends new patient data to the server.

Briefing

FastAPI’s “create” flow hinges on one practical idea: accept a POST request with a request body, validate it automatically with a Pydantic model, then merge the new resource into the JSON-backed “database” only if the incoming patient ID doesn’t already exist. That combination—POST + request body + Pydantic validation + server-side persistence—turns a messy, manual validation task into a structured endpoint that also generates clean interactive documentation.

After a quick recap of the patient-management project (CRUD-style operations with endpoints for listing, retrieving by patient ID via a path parameter, and sorting via query parameters), the focus shifts to creating new patients. The “create” endpoint uses an HTTP POST method because the client is sending new data to the server rather than requesting data. Along with the POST request, the client sends patient details in a JSON request body—fields like name, gender, city, age, height, and weight. In FastAPI terms, that payload is the request body: the portion of an HTTP request that carries structured data from client to server, commonly used with methods like POST and PUT.

The core engineering work starts with building a Pydantic model for the incoming payload. The model defines required fields and adds constraints and metadata so both validation and documentation improve. The transcript walks through creating a Patient model that includes an ID (as a string), name and city (strings), age (integer with a range constraint), gender (restricted to allowed literal options such as male/female/others), and height/weight (floats constrained to be greater than zero). Descriptions and examples are added using typing annotations so the auto-generated docs show meaningful guidance.

Two additional fields—BMI and verdict—are not expected from the client. Instead, they’re computed automatically using Pydantic computed fields. BMI is calculated from weight divided by height squared, rounded to two decimals. Verdict is derived from BMI thresholds (underweight, normal, overweight, obese) using conditional logic. Because computed fields depend on other validated inputs, they’re triggered automatically once the model has the required height and weight.

With the model ready, the create endpoint is implemented as an app.post route at /create. The endpoint function receives the request body as a Patient Pydantic object, meaning validation happens before the endpoint logic runs. The server then loads existing patient data from the JSON file, checks whether the incoming patient ID already exists, and if it does, raises an HTTP 400 error (“patient already exists”). If the ID is new, the endpoint merges the new patient into the existing dictionary—converting the Pydantic object to a dict while excluding the ID from the value portion—then saves the updated structure back to the JSON file.

Finally, the endpoint is tested through FastAPI’s interactive docs. Submitting an existing ID returns 400, while submitting a new ID returns a 200 success response. The created record shows that BMI and verdict were computed server-side automatically, confirming that Pydantic handled both validation and derived-field logic without requiring the client to send those fields. The next steps are queued for update and delete endpoints.

Cornell Notes

The create endpoint in FastAPI uses a POST request plus a JSON request body to add a new patient to a JSON-backed database. A Pydantic Patient model validates incoming fields (types, required-ness, and constraints like age range and positive height/weight) and enriches the API docs with descriptions and examples. BMI and verdict are computed automatically via Pydantic computed fields, so the client sends only height/weight and gender/age/etc., not derived values. The endpoint loads existing records, rejects duplicate patient IDs with an HTTP 400, merges the new patient into the stored dictionary, saves the updated JSON, and returns a success response. This pattern reduces manual validation code and makes the API self-documenting.

Why does the create operation use HTTP POST instead of GET in this patient API?

Create sends new data from client to server, so the request method must carry a payload. GET is used for retrieval, where the server responds with data. Here, the client posts patient details (name, gender, city, age, height, weight, and patient ID) in JSON, and the server persists a new record if the ID is not already present.

What exactly is a “request body,” and how does it relate to FastAPI endpoints?

A request body is the part of an HTTP request that contains structured data sent by the client to the server. In this workflow, the client includes patient fields in JSON, and FastAPI maps that JSON into a Pydantic model parameter in the endpoint function. That model then performs validation before the endpoint logic runs.

How does Pydantic validation prevent bad data from reaching the create logic?

The Patient Pydantic model marks fields as required and applies constraints. For example, age must be an integer greater than 0 and less than 120; height and weight must be floats greater than 0; gender is restricted to allowed literal options (male, female, others). If the client sends invalid types (like age as a string), validation fails and the endpoint doesn’t proceed to persistence.

How are BMI and verdict handled if the client does not send them?

BMI and verdict are implemented as computed fields. BMI is calculated from weight and height (weight / height²), rounded to two decimals. Verdict is derived from BMI thresholds using conditional logic (underweight/normal/overweight/obese). Because computed fields depend on validated inputs, they’re computed automatically when the Pydantic model is created from the request body.

What prevents duplicate patient IDs from being stored?

After loading existing data from the JSON file, the endpoint checks whether the incoming patient ID already exists as a key in the stored dictionary. If it does, it raises an HTTPException with status code 400 and a message indicating the patient already exists. Only when the ID is new does the endpoint merge and save the record.

How does the endpoint persist the new patient into the JSON file?

The endpoint converts the validated Pydantic patient object into a dictionary (using model_dump) and excludes the ID from the value portion. It then inserts the remaining patient attributes under the patient ID key in the existing dictionary. Finally, it writes the updated dictionary back to the JSON file using json.dump, and returns a JSON response with a success status code (2001 in the transcript) and a message.

Review Questions

  1. What fields are required in the Patient Pydantic model, and what constraints are applied to age, height, and weight?
  2. How do computed fields ensure BMI and verdict are available in the stored record without being sent by the client?
  3. What exact checks and error handling occur when a client tries to create a patient with an ID that already exists?

Key Points

  1. 1

    Use app.post for the create endpoint because the client sends new patient data to the server.

  2. 2

    Treat the incoming JSON payload as a request body and map it directly into a Pydantic model parameter for automatic validation.

  3. 3

    Define required fields and constraints in the Pydantic model (e.g., age range, positive height/weight, and restricted gender values).

  4. 4

    Implement BMI and verdict as Pydantic computed fields so derived values are calculated server-side from validated inputs.

  5. 5

    Load existing patient records from the JSON file, reject duplicate patient IDs with an HTTP 400, and only then merge the new patient.

  6. 6

    Convert the validated Pydantic object to a dict for storage, excluding the ID from the value portion so the ID remains the dictionary key.

  7. 7

    Return a structured JSON response after saving, and verify behavior using FastAPI’s interactive Swagger docs (Try it out).

Highlights

The create endpoint relies on POST + request body + Pydantic validation, so invalid payloads never reach the persistence step.
BMI and verdict are computed automatically via Pydantic computed fields, meaning clients don’t need to send derived values.
Duplicate patient IDs are blocked by a dictionary-key check and an HTTP 400 error before any JSON write occurs.
FastAPI’s auto-generated docs reflect the Pydantic model’s descriptions, constraints, and required request body structure.

Topics

Mentioned

  • Nitesh Gupta
  • HTTP
  • JSON
  • API