from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_root(item_id):
return {"item_id": item_id}
http://127.0.0.1:8000/items/foo로 가면 다음과 같은 응답을 준다.
{"item_id":"foo"}
타입을 지정할수도 있다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_root(item_id: int):
return {"item_id": item_id}
http://127.0.0.1:8000/items/3으로 가면?
{"item_id":3}
이전 url로 가면, 다음과 같은 에러를 보인다. (데이터 검증)
{"detail":[{"loc":["path","item_id"],"msg":"value is not a valid integer","type":"type_error.integer"}]}
만약 경로 매개변수를 사용한 후에, 동일한 주소뒤에 특정 단어가 들어가는 주소를 사용하고 싶다면 순서를 앞에 적어야 한다. 예를 들어,
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}
사전정의 (Enum 클래스 생성)
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name is 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"}
return {"model_name": model_name, "message": "Have some residuals"}
Enum 클래스 생성
from enum import Enum
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
경로 매개변수 선언
async def get_model(model_name: ModelName):
Enum 이해할 것!
전체 코드
from fastapi import FastAPI
from enum import Enum
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/items/{item_id}")
def read_root(item_id: int):
return {"item_id": item_id}
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
print(model_name)
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
'Framework, Library > Fast api' 카테고리의 다른 글
| [Fast api] Query Parameters and String Validations (0) | 2023.04.27 |
|---|---|
| [Fast_api] Request Body (0) | 2023.04.27 |
| [Fast_api] 쿼리 매개변수 (0) | 2023.04.27 |
| [Fast_api] start (0) | 2023.04.27 |
| [Fast_api] fast_api란? (0) | 2023.04.24 |