Task:
- Create a FastAPI application.
- Define a Pydantic model called
Item
with two fields:name
(string) andprice
(float). - Define another model
Cart
, which includes a list ofItem
instances. - Create a POST endpoint
/cart
that accepts aCart
request body and returns it as a response.
Example Input (JSON):
{
"items": [
{"name": "Laptop", "price": 1200.50},
{"name": "Mouse", "price": 25.99}
]
}
Expected Output (JSON):
{
"items": [
{"name": "Laptop", "price": 1200.50},
{"name": "Mouse", "price": 25.99}
]
}
Task:
- Extend
Item
to add:price
must be greater than 0.name
must be at least 3 characters long.
- In
Cart
, ensure that theitems
list contains at least oneItem
. - Return a
400 Bad Request
error if any validation fails.
Example Invalid Input (JSON):
{
"items": [
{"name": "PC", "price": -500}
]
}
Expected Response (400 Bad Request):
{
"detail": [
{
"loc": ["body", "items", 0, "price"],
"msg": "Price must be greater than 0",
"type": "value_error"
}
]
}
Task:
- Create a new model
User
, with fields:username
(string, min 3 chars)email
(valid email format)
- Modify
Cart
to include auser
field of typeUser
. - Update the
/cart
endpoint to return both the user and items.
Example Input (JSON):
{
"user": {
"username": "john_doe",
"email": "[email protected]"
},
"items": [
{"name": "Keyboard", "price": 45.00},
{"name": "Monitor", "price": 250.00}
]
}
Expected Output (JSON):
{
"user": {
"username": "john_doe",
"email": "[email protected]"
},
"items": [
{"name": "Keyboard", "price": 45.00},
{"name": "Monitor", "price": 250.00}
]
}
Task:
- Extend the
/cart
endpoint to calculate the total price of items. - If the total price is greater than $500, apply a 10% discount.
- Return the
total_price
(after discount, if applicable) in the response.
Example Input (JSON):
{
"user": {
"username": "jane_doe",
"email": "[email protected]"
},
"items": [
{"name": "Gaming Laptop", "price": 1200.00},
{"name": "Headset", "price": 50.00}
]
}
Expected Output (JSON):
{
"user": {
"username": "jane_doe",
"email": "[email protected]"
},
"items": [
{"name": "Gaming Laptop", "price": 1200.00},
{"name": "Headset", "price": 50.00}
],
"total_price": 1125.00
}
(A 10% discount is applied to the total price of $1250, reducing it to $1125.)