-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexaample.py
70 lines (57 loc) · 1.78 KB
/
exaample.py
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
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items")
async def items():
return {"message": "127.0.0.0:8000/items"}
# Item_id passed as Path Parameter of Type Integer
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
# Restricted set of users allowed as Path Parameters - using Enum
from enum import Enum
class Users(str, Enum):
vivek = "Vivek"
gupta = "Gupta"
epidemiologist = "Epidemiologist"
@app.get("/users/{user_name}")
async def users(user_name: Users):
return {"user": user_name}
# Both Path Parameter (item_id) and Query Parametrs:
# needy, a required str.
# skip, an int with a default value of 0.
# limit, an optional int
from typing import Optional
@app.get("/items2/{item_id}")
async def read_user_item(
item_id: str,
needy: str,
skip: int = 0,
limit: Optional[int] = None):
item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
return item
# JSON Requesst Body
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/add_items/{item_id}")
async def create_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
# Form Data
from fastapi import Form
@app.post("/login_form/")
async def loginForm(username: str = Form(...), password: str = Form(...)):
return {"username": username,
"logged_in": True }
# Files
from fastapi import UploadFile, File
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename,
"content_type": file.content_type}
# Model Validation using Pydantic