fast api

yun·2024년 11월 27일

fast api 설치하기

python -m vnev venv
source venv/bin/activate
가상환경 설정까지는 똑같다.

설치하기

pip install fastapi
pip install "uvicorn[standard]"

uvicorn은 장고의 manage.py와 같은 역할인 듯 하다. 서버를 실행해볼 때 필요

파일 만들기

main.py

fastapi import하기

from typing import Union
from fastapi import FastAPI

app = FastAPI()

서버 실행방법

uvicorn main:app --reload

main.py에 있는 app 객체를 실행한다는 뜻이다 실행할 때마다 위의 명령어를 모두 입력하기 번거로우니 run.bat이라는 폴더를 따로 만들어 위의 명령어를 붙여넣은 후 터미널에 run.bat을 입력하면 실행을 할 수 있다.

main.py 에 다음과 같이 입력해보자.

from typing import Union
from fastapi import FastAPI

app = FastAPI()


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


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

서버를 실행하면

{
  "Hello": "World"
}

가 화면에 나타나게 된다.

http://127.0.0.1:8000/items/1 을 입력하면 밑에와 같은 화면이 나타난다.

{
  "item_id": 1,
  "q": null
}

http://127.0.0.1:8000/items/1?q=hello 로 바꿔 입력하면 밑에와 같은 화면이 나타난다.

{
  "item_id": 1,
  "q": "hello"
}

http://127.0.0.1:8000/docs
자동 대화형 API 문서를 볼 수 있다.

http://127.0.0.1:8000/redoc
다른 자동 문서를 볼 수 있다.

0개의 댓글