Task:
- Create a FastAPI application.
- Define a Pydantic model called
Itemwith two fields:name(string) andprice(float). - Define another model
Cart, which includes a list ofIteminstances. - Create a POST endpoint
/cartthat accepts aCartrequest 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
Itemto add:pricemust be greater than 0.namemust be at least 3 characters long.
- In
Cart, ensure that theitemslist contains at least oneItem. - Return a
400 Bad Requesterror 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
Cartto include auserfield of typeUser. - Update the
/cartendpoint 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
/cartendpoint 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.)