[FastAPI] FastAPI 활용하기

Jaeyeon Kim·2023년 6월 25일
1

FastAPI

목록 보기
2/4
post-thumbnail

FastAPI에 대한 간략한 설명과 설치 및 실행 방법은 이전 포스트에서 볼 수 있다.

Fast API 활용하기

요청 시 인자로 값 넘겨주기

API에 값을 담아서 보낼 땐 url에 넘기거나, query parameter를 사용하거나 body에 넣어서 보낼 수도 있다.

URL로 넘기기

# main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"message": "Hello World"}


@app.get("/home/{parameter}")
def home(parameter: str):
    return {"message": parameter}

위와 같이 코드를 작성하고 실행시키면,

위와 같이 사용할 수 있다.

Query parameter로 넘기기

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"message": "Hello World"}


@app.get("/home/")
def home(skip: int = 0, limit: int = 10):
    return skip, limit

위와 같이 사용하면 쿼리로 원하는 값을 전달할 수 있다.

아무 인자도 주지 않았을 때의 응답은 위와 같고,

하나만 줄 땐 위와 같이 ?skip=5를 붙여 전달할 수 있고,

여러개를 줄 땐 &로 묶어서 전달하면 된다.

Body에 담아서 넘기기

from fastapi import FastAPI
from typing import Union
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None


app = FastAPI()


@app.post("/items/")
def create_item(item: Item):
    return item

위와 같이 BaseModel를 import 해와서 받을 데이터의 타입을 지정해준다.

지정한 타입에 맞게 요청을 보내면 위처럼 response도 잘 오는 것을 알 수 있다.

profile
낭만과 열정으로 뭉친 개발자 🔥

1개의 댓글

comment-user-thumbnail
2023년 7월 2일

https://melonplaymods.com/2023/06/10/katana-man-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/machine-gun-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/truck-with-open-trailer-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/aircraft-carriers-and-osprey-fighters-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/jormungandr-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/battleship-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/serro-ultraman-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/people-sandbox35-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/police-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/the-belqius-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/guns-and-map-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/simon-ghost-railynpc-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/naruto-baryon-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/star-wars-mod-for-melon-playground-3/
https://melonplaymods.com/2023/06/11/imperial-at-at-walker-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/0-55-million-ton-daqu-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/berserkfrede22-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/multiple-colors-su-34-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/cod-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/japan-of-the-future-mod-for-melon-playground/

답글 달기

관련 채용 정보