본문 바로가기
개발/FastAPI

[FastAPI] FastAPI 시작하기 도입부~쿼리 매개변수

by devhooney 2023. 5. 15.
728x90

회사에서 Python + FastAPI로 개발을 하게 되었다.

그래서 공식문서를 훑어보았다.

 

1. 도입부

(1) 설치

- 가상환경에서 할 지 말지는 자기마음이지만, 가상환경에서 하는것이 여러 프로젝트를 할 때 깔끔하게 가능

pip install fastapi
pip install uvicorn

 

2. 첫걸음

(1) 시작하기

- main.py 생성 후 아래 코드 작성

from fastapi import FastAPI

app = FastAPI()


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

- app 변수는 FastAPI 클래스의 인스턴스

- app.get("/")은 HTTP 메소드 중 하나인 get

* 참고

  • POST: 데이터를 생성하기 위해.
  • GET: 데이터를 읽기 위해.
  • PUT: 데이터를 업데이트하기 위해.
  • DELETE: 데이터를 삭제하기 위해.

FastAPI는 기본적으로 비동기를 지원

 

- 실행

uvicorn main:app --reload

 

* 참고

uvicorn main:app 명령은 다음을 의미합니다:

main: 파일 main.py (파이썬 "모듈").
app: main.py 내부의 app = FastAPI() 줄에서 생성한 오브젝트.
--reload: 코드 변경 후 서버 재시작. 개발에만 사용.

 

(2) 확인하기

브라우저 실행하여 127.0.0.1:8000 접속하면

{"message": "Hello World"}

FastAPI 는 Swagger UI를 제공하기 때문에

127.0.0.1:8000/docs 로 접속하면 작성한 API 문서를 볼 수 있다.

 

3. 경로 매개변수

(1) 기본

- main.py

from fastapi import FastAPI

app = FastAPI()


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

- 코드 작성 후 127.0.0.1:8000/items/hooney 접속하면

{"item_id":"hooney"}

확인 가능

 

(2) 타입이 있는 매개변수

 

from fastapi import FastAPI

app = FastAPI()


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

- 타입을 int로 주었기 때문에 int 값만 입력가능

- 127.0.0.1:8000/items/5 접속하면

{"item_id":5}

 

(3) 순서 문제

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

- 이 경우 순차적으로 동작하기 때문에 /users/me를 입력하고 싶다면 위 처럼 먼저 선언해주어야 한다.

 

(4) Enum 클래스 이용한 사전정의 값

from enum import Enum

from fastapi import FastAPI


class ModelName(str, Enum):
    a = "aaa"
    b = "bbb"
    c = "ccc"


app = FastAPI()


@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    if model_name is ModelName.aaa:
        return {"model_name": model_name, "message": "aaa!"}

    if model_name.value == "bbb":
        return {"model_name": model_name, "message": "bbb"}

    return {"model_name": model_name, "message": "ccc"}

* 참고

열거형은 파이썬 3.4 이후 가능

 

 

4. 쿼리 매개변수

(1) 기본

- main.py

from fastapi import FastAPI

app = FastAPI()

result = [{"item_name": "a"}, {"item_name": "b"}, {"item_name": "c"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return result[skip : skip + limit]

기본값이 skip = 0, limit = 10이므로

127.0.0.1:8000/items/로 접속하면

127.0.0.1:8000/items/?skip=0&limit=10로 접속한 거와 같다.

 

(2) 선택적 매개변수

from typing import Union

from fastapi import FastAPI

app = FastAPI()


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

- item_id는 경로 매개변수

- q는 쿼리 매개변수로 값이 없을 경우 None으로 처리한다.(있는 경우 String으로 처리)

* 참고

파이썬에서 null은 None으로 표시

 

 

 

- 참고

https://fastapi.tiangolo.com/ko/tutorial/query-params/

728x90