FASTAPI 시작하기 (2) - Request Parameter

code_able·2023년 3월 12일
0
post-custom-banner

오늘은 fastapi로 request parameter를 정의하겠다.

PATH PARAMTER

기본 path parameter

@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

타입이 정해진 path parameter

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

Query Parameter

기본 parameter

@app.get('/items/')
async def read_item(skip:int=0, limit:int=10):
    return {skip:limit}


http://127.0.0.1:8000/items/?skip=0&limit=10

Optional parameter

@app.get('/items/{item_id}')
async def read_item(item_id:str, q:Optional[str]=None):
    if q:
        return {item_id:q}
    return {'item_id':item_id}


http://localhost:8000/items/myItem?q=aa

Pydantic RequestBody

json body는 pydantic으로 표현 할 수 있다.

from typing import Optional
from pydantic import BaseModel, Field
from fastapi import FastAPI

app = FastAPI()

class Item(BaseModel):
    name :str = Field('', title='item name', max_length=254)
    description : Optional[str] = Field(
        None, title="The description of the item", max_length=300
    )
    price : float = Field(0, title='item price')

@app.post('/items/')
async def read_items(item:Item):
    return {'item' : 'item'} 
from typing import Optional
from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get('/items/')
async def read_item(ads_id: Optional[str] = Cookie(None)):
    return {'ads_id' : ads_id}

header Parameter

from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/items/")
async def read_items(user_agent: str = Header(None)):
    return {"User-Agent": user_agent}
profile
할수 있다! code able
post-custom-banner

0개의 댓글