-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
257 lines (202 loc) · 5.9 KB
/
main.py
File metadata and controls
257 lines (202 loc) · 5.9 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from models import EventCreate, BookingCreate, Event, Booking, ApiResponse
import business_logic
from storage import get_storage
# Create the FastAPI app
app = FastAPI(
title="Ticketing System",
description="An in-memory ticketing system for events",
version="1.0.0"
)
# ============= ERROR HANDLERS =============
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request, exc):
"""Handle validation errors (like wrong data type)"""
errors = exc.errors()
first_error = errors[0] if errors else {}
field = " -> ".join(str(loc) for loc in first_error.get("loc", []))
message = first_error.get("msg", "Validation error")
return JSONResponse(
status_code=422,
content={
"success": False,
"message": f"Validation error in {field}: {message}",
"data": None
}
)
# ============= EVENT ENDPOINTS =============
@app.post("/events", status_code=201)
def create_event_endpoint(event_data: EventCreate):
"""
CREATE EVENT
Example request:
POST /events
{
"name": "Rock Concert",
"date_time": "2026-12-31T20:00:00",
"venue": "Stadium",
"total_seats": 1000
}
"""
try:
event = business_logic.create_event(event_data)
return {
"success": True,
"message": "Event created successfully",
"data": event
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/events")
def list_events_endpoint():
"""
LIST ALL EVENTS
Example request:
GET /events
"""
events = business_logic.list_all_events()
return events # Returns list of events
@app.get("/events/{event_id}")
def get_event_endpoint(event_id: str):
"""
GET SINGLE EVENT
Example request:
GET /events/abc-123-def-456
"""
from uuid import UUID
event = business_logic.get_event(UUID(event_id))
if not event:
raise HTTPException(
status_code=404,
detail=f"Event {event_id} not found"
)
return {
"success": True,
"message": "Event found",
"data": event
}
@app.get("/events/{event_id}/availability")
def check_availability_endpoint(event_id: str):
"""
CHECK SEAT AVAILABILITY
Example request:
GET /events/abc-123-def-456/availability
"""
from uuid import UUID
available = business_logic.get_available_seats(UUID(event_id))
if available is None:
raise HTTPException(
status_code=404,
detail=f"Event {event_id} not found"
)
return {
"success": True,
"message": f"{available} seats available",
"event_id": event_id,
"available_seats": available
}
@app.post("/bookings", status_code=201)
def create_booking_endpoint(booking_data: BookingCreate):
"""
CREATE BOOKING (Book seats!)
Example request:
POST /bookings
{
"event_id": "abc-123-def-456",
"num_seats": 2
}
"""
booking, error = business_logic.create_booking(booking_data)
if error:
# Determine error type
if "not found" in error.lower():
status_code = 404
elif "not enough" in error.lower():
status_code = 409 # Conflict
else:
status_code = 400
raise HTTPException(status_code=status_code, detail=error)
return {
"success": True,
"message": f"Booked {booking.num_seats} seat(s) successfully",
"data": booking
}
@app.get("/bookings/{booking_id}")
def get_booking_endpoint(booking_id: str):
"""
GET BOOKING DETAILS
Example request:
GET /bookings/xyz-789-abc-123
"""
from uuid import UUID
booking = business_logic.get_booking(UUID(booking_id))
if not booking:
raise HTTPException(
status_code=404,
detail=f"Booking {booking_id} not found"
)
return {
"success": True,
"message": "Booking found",
"data": booking
}
@app.patch("/bookings/{booking_id}/cancel")
def cancel_booking_endpoint(booking_id: str):
"""
CANCEL BOOKING
Example request:
PATCH /bookings/xyz-789-abc-123/cancel
"""
from uuid import UUID
success, error = business_logic.cancel_booking(UUID(booking_id))
if not success:
status_code = 404 if "not found" in error.lower() else 400
raise HTTPException(status_code=status_code, detail=error)
booking = business_logic.get_booking(UUID(booking_id))
return {
"success": True,
"message": f"Booking cancelled, {booking.num_seats} seat(s) returned",
"data": booking
}
# ============= UTILITY ENDPOINTS =============
@app.get("/")
def root():
"""
ROOT / WELCOME
Just shows API is running
"""
return {
"success": True,
"message": "Ticketing System API is running!",
"documentation": "/docs",
"endpoints": {
"events": "/events",
"bookings": "/bookings"
}
}
@app.get("/health")
def health_check():
"""
HEALTH CHECK
Shows stats about the system
"""
storage = get_storage()
return {
"success": True,
"status": "healthy",
"stats": {
"total_events": len(storage.events),
"total_bookings": len(storage.bookings)
}
}
# ============= STARTUP MESSAGE =============
@app.on_event("startup")
def startup():
print("\n" + "="*50)
print(" TICKETING SYSTEM API STARTED")
print("="*50)
print(" API Documentation: http://localhost:8000/docs")
print(" Test it: http://localhost:8000/")
print("="*50 + "\n")