Path Parameters
item_id 를 통한 인자 설정
You can declare path parameters or variables with the same syntax used by Python format strings
경로의 파라미터들이나 변수들을 Python format strings 을 사용하여 정의할 수 있다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
The value of the path parameter item_id will be passed to your function as the argument item_id.
item_id 경로 파라미터의 값은 함수의 item_id 인자로 전달된다.
So, if you run this example and go to
http://127.0.0.1:8000/items/foo
you will see a response
{"item_id":"foo"}
Path parameter with types
you can declare the type of a path parameter in the function, using standard Python type annotations:
Python annotations type을 이용하여서 인자의 타입을 정의할 수 있다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
In this case, item_id is declared to be an int.
This will give your editor support inside of your function, with erre checks, completion, etc.
Data Conversion
If you run this example and open your browser at
http://127.0.0.1:8000/items/3
you will see a response of
{"item_id":3}
Notice that the value your function received (and returned) is 3, as a Python int, not a string "3"
So, with that type declaration, FastAPI gives you automatic request "parsing"
string 3이 아니라 int 3으로 변환해준다. FastAPI는 자동으로 request parsing을 제공한다.
Data Validation
데이터 검증
But if you go to the browser at http://127.0.0.1:8000/items/foo, you will see a nice HTTP error of:
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
HTTP 에러가 다음과 같이 일어나게 된다.
because the path parameter item_id had a value of "foo" which is not an int.
경로 파라미터 item_id 가 int가 아닌 foo를 가졌기 때문이다.
The same error would appear if you provided a float instead of an int, as in: http://127.0.0.1:8000/items/4.2
int 대신 float를 넣었어도 같은 에러가 발생하게 된다.
So, with the same Python type declaration, FastAPI gives you data validation.
Notice that the error also cleary state exactly the point where the validation didn't pass
error는 어디에서 검증이 되지 않았는지에 대한 포인트를 정확하게 state를 통해 알려준다.
This is inredibly helpful while developting and debugging code that interacts with you API.
Documentation
And when you open your browser at http://127.0.0.1:8000/docs you will see an automatic, interactive, API documentation.
Again just with the same Python type declaration, FastAPI gives you automatic, interactive docuementation(integrating Swagger UI)
Notice that the path parameter is declared to be an integer.
자동적이고 상호작용가능한 API 문서가 생성이 된다.
Standards-based benefits, alternative documentation
And because the generated schema is from the OpenAPI standard, there are many compatible tools.
생성된 schema의 형태는 OpenAPI의 표준을 따르고 있다. 많은 호환성 툴이 존재한다.
Because of this, FastAPI itself provides an alternative API documentation(using ReDoc), which you can access at http://127.0.0.1:8000/redoc
FastAPI 자체에서 ReDoc을 사용하여 대체 API 문서를 제공하고 있다. redoc을 통해서 접근 가능하다.
The same way, there are many compatible tools, including code generation tools for many languages.
Pydantic
All the data validation is performed under the hood by https://pydantic-docs.helpmanual.io/
모든 데이터 검사에 대해서 pydantic 아래에 수행되고 있습니다.
so you get all the benefits from it.
And you know you are in good hands.
You can use the same type declarations with str, float, bool and many other complex data types.
Several of these are explored in the next chapters of the tutorial
순서 문제들 (Order matters)
When creating path operations, you can find situations where you have a fixed path.
Like /users/me, let's say that it's to get data about the current user.
/users/me 현재 사용자에 대한 정보를 받아올 수 있다.
And then you can also have a path /users/{user_id} to get data about a specific user by some user ID.
/users/{user_id}라는 특정 유저에 대한 id를 받을 수 있다.
Because path operations are evaluated in order, you need to make sure that the path for /users/me is declared before the one for /users/{user_id}
path operations 들은 순서로 평가된다. /users/me에 대한 정의는 /users/{users_id} 전에 미리 나와야한다.
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}
Otherwise, the path for /users/{user_id} would match also for /users/me, "thinking" that it's receiving a parameter user_id with a value of "me".
순서가 저렇지 않으면 user_id의 값으로 me로 받고있다고 생각합니다.
Simliarly, you cannot redefine a path operation.
비슷하게, 한개의 path operation을 재정의할 수 없습니다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
async def read_users():
return ["Rick", "Morty"]
@app.get("/users")
async def read_users2():
return ["Bean", "Elfo"]
The first one will always be used since the path matches first.
Predefined values
If you have a path operation that recevies a path parameter, but you want the possible valid path parameter values to be predefined, you can use a standard Python enum.
path 인자를 받는 하나의 path operation이 있고, 유효한 path 인자 값들을 미리 정의된 값으로 하기를 원한다면, Python enum을 사용할 수 있다.
Create an Enum class
Import Enum and create a sub-class that inherits from str and from Enum .
Enum을 import 하고, str와 Enum 상속한 서브클래스를 생성해주세요.
By inheriting from str the API docs will be able to know that the values must be of type string and will be able to render correctly.
str을 상속함으로써 API docs는 값들이 string만 가능하며, 그리고 올바르게 랜더링 될 것입니다.
Then create class attributes with fixed values, which will be the available valid values:
수정된 값과 이용가능한 유효한 값들을 class attritbutes을 생성하세요.
model_name is ModelName.alexnet
model_name.value == "lenet"
2가지 방법으로 표현될 수 있다.
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"}
Declare a path parameter
Then create a path parameter with a type annotation using the enum class you created(ModelName):
enum class를 사용한 ModelName의 annotation 타입과 함께 path parameter를 생성하였다.
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"}
댓글