-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
100 lines (85 loc) · 3 KB
/
backend.py
File metadata and controls
100 lines (85 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import json
import random
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
# --- 1. SETUP ---
app = FastAPI(
title="Mission Pizza API",
description="A legacy REST API for ordering pizzas. Use this to place orders and check status.",
version="1.0.0"
)
# --- 2. MOCK DATABASE ---
# In a real app, this would be SQL. Here, it's just memory.
MENU_DB = [
{"name": "Margherita", "price": 10.99, "tags": ["vegetarian", "classic"]},
{"name": "Pepperoni", "price": 12.99, "tags": ["meat", "popular"]},
{"name": "Hawaiian", "price": 13.50, "tags": ["controversial", "pineapple"]},
{"name": "Veggie Supreme", "price": 11.50, "tags": ["vegetarian", "loaded"]},
{"name": "Spicy Alertness", "price": 14.00, "tags": ["spicy", "exam-fuel"]}
]
ORDERS_DB = {}
# --- 3. DATA MODELS (Pydantic) ---
class Pizza(BaseModel):
name: str
price: float
tags: List[str]
class OrderRequest(BaseModel):
pizza_name: str
quantity: int = 1
customer_name: str
class OrderResponse(BaseModel):
order_id: str
status: str
estimated_delivery_time: str
total_price: float
# --- 4. ENDPOINTS ---
@app.get("/menu", response_model=List[Pizza], operation_id="get_menu")
def get_menu():
"""
Get the list of available pizzas.
"""
return MENU_DB
@app.post("/order", response_model=OrderResponse, operation_id="place_order")
def place_order(order: OrderRequest):
"""
Place a new pizza order. Returns order ID and estimated time.
"""
# Find pizza
pizza = next((p for p in MENU_DB if p["name"].lower() == order.pizza_name.lower()), None)
if not pizza:
raise HTTPException(status_code=404, detail="Pizza not found on menu")
# Generate Mock ID and Time
order_id = f"ord-{random.randint(1000, 9999)}"
delivery_time = f"{random.randint(30, 60)} mins"
# Save to Mock DB
new_order = {
"order_id": order_id,
"status": "cooking",
"estimated_delivery_time": delivery_time,
"total_price": pizza["price"] * order.quantity,
"items": f"{order.quantity}x {pizza['name']}"
}
ORDERS_DB[order_id] = new_order
return new_order
@app.get("/order/{order_id}", response_model=OrderResponse, operation_id="get_order_status")
def get_order_status(order_id: str):
"""
Check the status of an existing order by ID.
"""
order = ORDERS_DB.get(order_id)
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return order
# --- 5. UTILITY TO DUMP OPENAPI JSON ---
if __name__ == "__main__":
# When run directly, this script saves the JSON spec to a file
import sys
if len(sys.argv) > 1 and sys.argv[1] == "generate_spec":
with open("pizza_api.json", "w") as f:
json.dump(app.openapi(), f, indent=2)
print("✅ pizza_api.json generated successfully!")
else:
# Otherwise run the server
uvicorn.run(app, host="0.0.0.0", port=8080)