# type_hint.py
def add(n1: int, n2: int) -> int:
return n1 + n2
sample_list: List[int] = [1, 2, 3, 4]
sample_dict: Dict[str, str] = { "user" : "이도운" }
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return { "message" : "Hello World" }
127.0.0.1:8000/docs
@app.get("/country/{country_name}")
async def index(country_name: str):
return { "country" : country_name }
@app.get("/country/")
async def index(country_name: str = 'korea', country_no: int = 1):
return {
"country" : country_name,
"country_no" : country_no
}
from typing import Optional
@app.get("/country/")
async def index(country_name: Optional[str] = None, country_no: Optional[int] = None):
return {
"country" : country_name,
"country_no" : country_no
}
from pydantic import BaseModel
class Item(BaseModel):
name: str
desc: Optional[str] = None
price: int
tax: Optional[float] = None
app = FastAPI
@app.post("/item/")
async def create_item(item: Item):
return {"message" : f"{item.name}"}
import requests
import json
def main():
url = 'http://127.0.0.1:8000/item/'
body = {
"name" : "T-shirt",
"desc" : "string",
"price" : 5000,
"tax" : 1.2,
}
res = requests.post(url, json.dumps(body))
print(res.json())
【FastAPI超入門】直感的にWeb API開発ができるモダンなPython WebフレームワークFastAPIの基礎を80分でマスター