-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.py
More file actions
50 lines (36 loc) · 1.13 KB
/
example2.py
File metadata and controls
50 lines (36 loc) · 1.13 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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
# Let's create a Pydantic vehicle model
class Vehicle(BaseModel):
vehicle_id: int # avoid using `id` as it is a built-in python function
year: int
make: str
model: str
# All about that type hinting...
vehicles: list[Vehicle] = []
# Nit: __init__ does not have type hinting / IntelliSense with Pydantic
# see: https://github.com/microsoft/python-language-server/issues/1898
montero_sport = Vehicle(
vehicle_id = 1,
year = 2003,
make = 'Mitsubishi',
model = 'Montero Sport'
)
vehicles.append(montero_sport)
@app.get('/vehicles/', response_model=list[Vehicle])
def list_vehicles():
return vehicles
@app.get('/vehicles/{vehicle_id}/', response_model=Vehicle)
def get_vehicle(vehicle_id: int):
vehicle_index = vehicle_id - 1
try:
vehicle = vehicles[vehicle_index]
except IndexError:
raise HTTPException(404, 'Can\'t find a vehicle with that ID!')
else:
return vehicle
@app.post('/vehicles/')
def create_vehicle(data: Vehicle):
# Uh-h, somethings off...
vehicles.append(data)