from fastapi import FastAPI
app = FastAPI()
uvicorn main:app --reload
에서의 app이다.api_practice = FastAPI()
라고 만들면 uvicorn main:api_practice --reload
라고 입력해야 한다.path
란 첫 번째 /
에서 시작하는 URL의 마지막 부분https://example.com/items/foo
이 URL에서/items/foo
path
= endpoint
= route
operation
(동작)이란 HTTP 메소드를 말한다POST
, GET
, PUT
, DELETE
OPTIONS
, HEAD
, PATCH
, TRACE
도 있다@app.get("/")
의 의미 : /
path에서 GET
메소드로 요청을 처리하겠다async def
나 일반함수 def
로 정의할 수 있다return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
path parameter
인 item_id
값은 함수의 item_id
인자로 전달된다http://127.0.0.1:8000/items/OMG
이 경로로 이동하면 {"item_id":"foo"}
리턴값을 받게 된다.@app.get("/items/{item_id}")
async def read_item(item_id: int): # int로 선언
return {"item_id": item_id}
item_id
를 int
형으로 선언할 수 있다http://127.0.0.1:8000/items/3
이 경로로 이동하면 {"item_id":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}
이 경우 operation은 순서대로 진행되기 때문에 /users/{user_id}
이전에 /users/me
를 먼저 선언해야 한다. 그렇지 않으면 /users/{user_id}
는 매개변수 user_id
의 값을 "me"라고 "생각하여" /users/me
로 연결합니다.
from enum import Enum
from fastapi import FastAPI
class MyModel(str, Enum):
alexnet = "amazing"
resnet = "wassup"
lenet = "wow"
app = FastAPI()
@app.get("/models/{model_name}")
def get_model(model_name: MyModel):
if model_name == MyModel.alexnet:
return {"model_name": model_name, "message": "result 1!"}
if model_name.value == "wassup":
return {"model_name": model_name, "message": "wassup guys"}
return {"model_name": model_name, "message": "Guten Tag!"}
Enum
을 import 하고 str
과 Enum
을 상속하는 서브 클래스 생성model_name
을 wow
로 선택하면 Request URL 은 http://127.0.0.1:8000/models/wow
이 되고 클라이언트는 결과 값으로 Response body에 {
"model_name": "wow",
"message": "Guten Tag!"
}
이 담겨서 결과값이 반환된다.
모델의 속성값에 접근하는 방법 ( 변수a 에 model이 선언되어 있다고 가정하고)
1.a == ModelName.속성
2.a.value == "value"
3.ModelName.속성.value
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
Query Parameters
로 자동 해석함?
뒤에 나오며 &
으로 구분되는 Key=Value
쌍의 집합이다http://127.0.0.1:8000/items/?skip=0&limit=10
에서 쿼리 매개변수는 skip 값 0이고 limit 값 10 이다. 다 문자열이지만 limit: int = 10
이렇게 선언할 경우 int
형으로 자동 변환된다.from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
{item_id}
가 /
뒤에 있기 때문에 패스 파라미터
로,q
는 경로에 표시되어 있지 않기 때문에 자동으로 쿼리 파라미터
로 인식한다from typing import Optional
from fastapi import FastAPI
prac2 = FastAPI()
@prac2.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
item = {"item_id": item_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
여기서 http://127.0.0.1:8000/items/foo?short=False
로 이동하면
{
"item_id": "12",
"description": "This is an amazing item that has a long description"
}
리턴값이 반환되고
http://127.0.0.1:8000/items/foo?short=True
로 이동하면
{
"item_id": "12"
}
이 반환된다. 1
, true
, on
, yes
도 True
로 인식한다
from typing import Optional
from fastapi import FastAPI
prac2 = FastAPI()
@prac2.get("/items/{item_id}")
async def read_user_item(
item_id : str,
needy : str,
skip : int = 0,
limit : Optional[int] = None
):
item = {
"item_id" : item_id,
"needy" : needy,
"skip" : skip,
"limit" : limit
}
return item
http://127.0.0.1:8000/items/pants?needy=wow&skip=0
item_id
는 문자형으로 입력되어야 하며 패스파라미터
로 필수값이다.needy
역시 문자형으로 입력되어야 하며 쿼리파라미터
로 필수 값이다skip
은 숫자형으로 입력되어야 하며 쿼리파라미터
이며 선택값이고 디폴트가 0 이다.limit
도 숫자형으로 입력되어야 하며 쿼리파라미터
이며 선택값이며