-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-tutorial-session-1-6.py
More file actions
143 lines (119 loc) · 4.98 KB
/
main-tutorial-session-1-6.py
File metadata and controls
143 lines (119 loc) · 4.98 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
from enum import Enum
from fastapi import FastAPI, Response, Query, Path
from pydantic import BaseModel
app = FastAPI()
@app.get("/")
async def root():
return{"Hello World"}
@app.post("/")
async def post():
return{"message": "hello from the post message"}
@app.put("/")
async def put():
return{"message": "hello from the put route"}
#it is important to note that it must use static route before the dynamic route
@app.get("/users/me")
async def get_current_user():
return {"message": "this is the current user"}
@app.get("/users/{user_id}")
async def get_user(user_id: str):
return {"user_id": user_id}
class FoodEnum(str, Enum):
fruits = "fruits"
vegatables = "vegatables"
diary = "diary"
@app.get("/foods/{food_name}")
async def get_food(food_name: FoodEnum):
if food_name == FoodEnum.vegatables:
return {"food_name": food_name, "message": "you are very healthy"}
if food_name == FoodEnum.fruits:
return {"food_name": food_name, "message": "you are still healthy but like sweet"}
else:
return {"food_name": food_name, "message": "I like milk"}
# fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
# @app.get("/items")
# async def list_items(skip: int = 0, limit: int = 10):
# return fake_items_db[skip : skip + limit]
@app.get("/items/{item_id}")
async def get_item(item_id: str, sample_query_param: str, q: str | None = None, short: bool = False):
item = {"item_id": item_id, "sample_query_param": sample_query_param}
if q:
item.update({"q": q})
if not short:
item.update({"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra."})
return item
@app.get("/users/{user_id}/items/{item_id}")
async def get_user_item(user_id: int, item_id: str, q: str | None = None, short: bool = False):
item = {"item_id": item_id, "owner_id": user_id}
if q:
item.update({"q": q})
if not short:
item.update({"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra."})
return item
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"Price_with_tax": price_with_tax})
return item_dict
@app.put("/items/{item.id}")
async def create_item_with_put(item_id: int, item: Item, q: str | None = None):
result = {"item_id": item_id, **item.dict()}
if q:
result.update({"q": q})
return result
@app.get("/items")
## the following is set the "q" become options - only valid for python 3.10 or later
# async def read_items(q: str | None = None):
## the following is set the query has default value, min and max lenght
# async def read_items(q: str = Query("fixedquery", min_length=3, max_length=10)):
## the following "..." can set as NO default value but the field is mandatory
# async def read_items(q: str = Query(..., min_length=3, max_length=10)):
## the following allows input multiple possible values. If require default vales, change the Query["Foo", "Bar"]
# async def read_items(q: list[str] | None = Query(["Foo", "Bar"])):
## the following shows multiple default fields can add to this function. One specific value call "alias", as defult the
## python not take "-" (hype) as the URL, however if use "alias", it will replace "q" to the name of "alias" in the URL
async def read_items(q: str | None = Query(
None,
min_length=3,
max_length=10,
title="Sample query string",
description="this is a sample query string",
deprecated=True,
alias="item-query"
)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
## The following example show how to hidden the query in the API.
@app.get("/items_hidden")
async def hidden_query_route(hidden_query: str | None = Query(None, include_in_schema=False)):
if hidden_query:
return {"hidden_query": hidden_query}
return {"hidden_query": "Not Found"}
## The following example show how to validate the input information.
@app.get("/items_validation/{item_id}")
## Use "(...)" it can set no default but input is mandatory.
# async def read_items_validation(
# item_id: int = Path(..., title= "The ID of items to get"),
# q: str | None = Query(None, alias="item-query")
# ):
## If put q:str after the item_id, Python will consider it is part of default value, so it makes "q: str" doesn't work.
## However, if add "*," above the items ID, it will tell Python that after "*,", all other parameter consider as query.
async def read_items_validation(
*,
item_id: int = Path(..., title= "The ID of items to get", gt=10, lt=100),
q: str,
size: float = Query(..., gt=0, lt=7.75)
):
results = {"item_id": item_id, "size": size}
if q:
results.update({"q": q})
return results