이 글은 Fast API 공식문서를 기반으로 학습한 내용들을 정리한 글이다
모든 학습 자료들은 아래 링크에서 찾아볼 수 있다
https://fastapi.tiangolo.com/

경로 매개변수
HTTP 메소드 데코레이터 바로 아래 있는 코드가 해당 요청을 처리할 때 실행된다.
@app.get()
@app.post()
@app.put()
@app.delete()
요청이 들어왔을 때 코드를 실행할 수 있는데, 이때 dict, list, str, int 등을 반환할 수 있다.
이때 Pydantic 모델, JSON으로 자동 변환되어 지원된다.
매개변수 또는 변수를 경로에 선언할 수 있다.
@app.get(“items/{item_id}”)
async def read_item(item_id):
return {“item_id” : item_id }
위의 경우에 경로 매개변수 item_id 값은 함수의 item_id 인자로 전달된다.
http://127.0.0.1:8000/items/foo 에 접속하면 아래와 같은 값이 화면에 도출된다.
{“item_id” : “foo”}
타입이 있는 매개변수
@app.get(“items/{item_id}”)
async def read_item(item_id: int):
return {“item_id” : item_id }
경로 매개변수의 타입을 선언할 수 있다. 위의 경우에는 인자로 받는 item_id를 int로 선언해주었다.
http://127.0.0.1:8000/items/3 에 접속하면 아래와 같은 값이 화면에 도출된다.
{“item_id” : 3 }
이때 경로 매개변수 값이 int인데, str이나 float로 들어올 시 HTTP 오류가 난다.
동작 순서
경로 동작은 순차적으로 평가되기 때문에 겹치지 않게 먼저 요청을 받을 순으로 선언해야한다.
@app.get(“/users/me”)
#def ~~
@app.get(“/users/{user_id}”)
#def ~~
위와 같은 경우는 http://127.0.0.1:8000/users/me 로 요청을 했을 때 순서에 따라 @app.get("/users/me")가 먼저 호출이 되어 작동된다.
사전 정의 값
경로 매개변수 외에 미리 정의할 수 있는 경로 매개변수 값을 원한다면 아래와 같이 Enum 클래스를 생성해서 사용할 수 있다.
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum) :
alexnet = “alexnet”
resent = “resnet”
lenet = “lenet”
@app.get(“/models/{model_name}”)
async def get_model(model_name: ModelName):
if model_name == ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == “lenet”:
return {"model_name": model_name, "message": "LeCNN all the images"}
경로를 포함하는 경로 매개변수
/file/{file_path}가 있는 경로 동작이 있을 시 파일 경로가 필요하므로 /home/download/file.txt 이러한 URL을 받을 것이다.
이때 경로 변환기로 /files/{file_path: path} 매개변수가 경로임을 알려줘야한다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}
'백엔드 > FastAPI' 카테고리의 다른 글
| [FastAPI] Pydantic이란? (0) | 2022.09.29 |
|---|---|
| [FastAPI] FastAPI 스터디 #3 (0) | 2022.09.29 |
| [FastAPI] FastAPI 스터디 #1 (0) | 2022.05.24 |