TIL | FastAPI 기본적인 지식

이도운·2022년 2월 1일

TIL

목록 보기
66/73
post-thumbnail

타입 힌트

# 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" : "이도운" }

FastAPI 시작하기

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}"}

API 호출

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分でマスター

profile
⌨️ 백엔드개발자 (컴퓨터공학과 졸업)

0개의 댓글