StaffCoder
FastAPI
FastAPIFastAPI 0.139Python 3.13
7 modules · 28 challengesSign up
Module 3 · Request Body and Pydantic Models

Booking Request Payload

easy—No data yet

Problem statement

A booking arrives as a trip in the URL, an agent code and a notify flag in the query, and a nested body holding one contact, a list of passengers and an optional extras section. The endpoint takes none of them and the request model flattens the body into loose fields. Declare all of it, so every value carries its own rules and a violation is reported at the exact place it happened.

Sample Data

The trips in app/store.py hold the ids 1_, _2, 3_, _5 and 8_, so _4 and 99 belong to no trip. Here is one trip record:

{
  "id": 2,
  "name": "Kyoto Autumn Circuit",
  "base_price": 815.5
}

API Endpoints to Implement

The four models live in app/models/booking.py.

Contact

Permits no key it does not declare.

  • full_name, text, required, at least 3_ and at most _60 characters.
  • email, text, required, matching the pattern ^[a-z0-9.]+@[a-z0-9]+[.][a-z]{2,3}$.
  • phone, text or null, optional, default null.

Passenger

A key it does not declare is ignored rather than refused, unlike the other three.

  • full_name, text, required, at least 3_ and at most _60 characters.
  • age, a whole number, required, at least 0_ and at most _120.
  • window_seat, a boolean, optional, default false.

Extras

Permits no key it does not declare.

  • insurance, a boolean, optional, default false.
  • baggage_kg, a number, optional, default 0_, at least _0 and at most 40.

BookingRequest

Permits no key it does not declare, trip_id included, even when it repeats the one in the URL.

  • contact, one Contact, required.
  • passengers, a list of Passenger, required, at least 1_ and at most _4 of them.
  • extras, one Extras or null, optional, default null. An omitted, null or empty extras section leaves both its fields at their defaults.

POST /trips/{trip_id}/bookings

  • trip_id comes from the URL as a whole number of at least 1.
  • agent_code comes from the query, text, required, matching the pattern ^AG-[0-9]{4}$.
  • notify comes from the query, a boolean, optional, default true.
  • Look the trip up with find_trip in app/services/bookings.py, then hand it with agent_code, notify and the booking to build_confirmation, which answers with the confirmation.
  • Response code: 201, and 201 only.
  • A trip id no trip holds is answered with 404 and the body {"detail": "Trip 4 was not found"}, naming the id that was asked for.
  • The URL, query and body rules are checked before the trip is looked up, so a broken rule is answered with 422 even when the trip does not exist.

Rejected requests

A violation anywhere is answered with 422 and one detail entry per broken rule, carrying the type and msg reported for that rule, the input that was received, and, for a length or a bound, a ctx. A missing field reports the object it was missing from as its input.

loc names the path to the offending value: ["path", "trip_id"], ["query", "agent_code"], ["body"] for the body itself, ["body", "contact", "email"] for a field of the contact, ["body", "passengers"] for the list, and ["body", "passengers", 1, "age"] for a field of one passenger.

A refused key reports extra_forbidden, worded Extra inputs are not permitted. A passenger list outside its size reports too_short or too_long, worded List should have at least 1 item after validation, not 0 and List should have at most 4 items after validation, not 5.

The rules must sit on the models and the parameters rather than be checked inside the handler, since the service publishes them at GET /openapi.json, where each section is a schema of its own, the body is required and closed, the query values report their pattern and their default, and 201 is the only response code the operation declares.

Sample Requests & Responses

POST /trips/2/bookings?agent_code=AG-1042

Request:

{
  "contact": {"full_name": "Mara Velez", "email": "mara.velez@voyage.co", "phone": "+351 912 345 678"},
  "passengers": [
    {"full_name": "Mara Velez", "age": 34, "window_seat": true},
    {"full_name": "Ines Duarte", "age": 29, "window_seat": false}
  ],
  "extras": {"insurance": true, "baggage_kg": 3.5}
}

Response (201 Created):

{
  "trip_id": 2,
  "trip_name": "Kyoto Autumn Circuit",
  "agent_code": "AG-1042",
  "notify": true,
  "contact": {"full_name": "Mara Velez", "email": "mara.velez@voyage.co", "phone": "+351 912 345 678"},
  "passenger_count": 2,
  "adult_count": 2,
  "passengers": [
    {"full_name": "Mara Velez", "age": 34, "window_seat": true},
    {"full_name": "Ines Duarte", "age": 29, "window_seat": false}
  ],
  "insurance": true,
  "baggage_kg": 3.5,
  "total_price": 1671.75
}

POST /trips/2/bookings?agent_code=AG-1042

Request:

{
  "contact": {"full_name": "Mara Velez", "email": "mara@voyage", "phone": "+351 912 345 678"},
  "passengers": [
    {"full_name": "Mara Velez", "age": 34, "window_seat": true},
    {"full_name": "Ines Duarte", "age": 130, "window_seat": false}
  ],
  "extras": {"insurance": true, "baggage_kg": 3.5},
  "trip_id": 2
}

Response (422 Unprocessable Entity):

{
  "detail": [
    {
      "type": "string_pattern_mismatch",
      "loc": ["body", "contact", "email"],
      "msg": "String should match pattern '^[a-z0-9.]+@[a-z0-9]+[.][a-z]{2,3}$'",
      "input": "mara@voyage",
      "ctx": {"pattern": "^[a-z0-9.]+@[a-z0-9]+[.][a-z]{2,3}$"}
    },
    {
      "type": "less_than_equal",
      "loc": ["body", "passengers", 1, "age"],
      "msg": "Input should be less than or equal to 120",
      "input": 130,
      "ctx": {"le": 120}
    },
    {
      "type": "extra_forbidden",
      "loc": ["body", "trip_id"],
      "msg": "Extra inputs are not permitted",
      "input": 2
    }
  ]
}

More in Request Body and Pydantic Models

See the module
Item Creation ModelThis problem covers describing the shape of the data a caller may send when adding an item, so the parts they leave out get sensible values and the parts they get wrong are refused by name.0%0 of 1 solvedeasyField Constrained OrderThis problem covers putting limits on each value an order carries, so a quantity, a price or a note outside what the business allows is refused before the order is ever placed.—No data yeteasyNested Shipment StructureThis problem covers describing data that has parts inside parts, an address and a list of parcels within one shipment, so a mistake anywhere is reported at the exact place it happened.—No data yeteasy

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.