-
Create a FastAPI application with an endpoint
/items/{item_id}that:- Takes
item_idas a path parameter (integer). - Accepts
categoryas a query parameter (string, optional). - Accepts
priceas a request body parameter (float). - Uses
Annotatedfor validation.
- Takes
-
The API should:
- Validate
item_idto be a positive integer. - Ensure
priceis greater than zero. - Return a response containing the processed parameters.
- Validate
- Use
Annotated[int, (Field/Path)]for validation. - Use
BaseModelfor request body validation.
- Create a FastAPI endpoint
/cart/that accepts a request body representing a shopping cart. - The request body should contain:
user_id(integer, required)items(list of strings, min 1 item)
- Return the received data as a response.
user_idshould be a positive integer.itemsshould be a non-empty list.
- Use
Annotatedfor validation. - Use
Field(min_items=1)to enforce at least one item.
- Extend the API by adding an
/order/endpoint that accepts nested models in the request body. - The request body should have:
customer_id(integer, positive)order_items(list of order objects)
- Each order object must contain:
product_id(integer, required)quantity(integer, min 1)price(float, must be positive)
- Use
Annotatedfor validation. - Ensure
order_itemsis a non-empty list.
- Define
OrderItemas a separateBaseModeland use it inside the main model.
- Create a
/invoice/endpoint that accepts a complex invoice request with optional fields. - The request body should include:
invoice_id(UUID)customer_details(nested model withname,email)products(list of nested models)
- Each product object must have:
product_id(integer, required)name(string, min 3 characters)price(float, must be positive)discount(optional, float, between 0-50%)tags(optional, list of strings)
- Use
Optionalfor nullable fields. Refer to thetyping.Optionalof Python. - Use
confloatto limit discount percentage. Refer to the Constrained types of Pydantic.
- Utilize
AnnotatedandFieldfor detailed validation. - Use
UUIDforinvoice_id. Refer to the UUID documentation.