Skip to main content

路由使用

基础使用​

from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items/")
async def get_item(item_id: int = Query(..., gt=0)):
return {"item_id": item_id}

参数详解​

来自chatgpt

get/post()​

  1. path(str):路由的路径部分,用于指定路由的URL路径。
  2. title(str):路由的标题,用于自动生成API文档。
  3. description(str):路由的描述,用于自动生成API文档。
  4. summary(str):路由的摘要,用于自动生成API文档。
  5. deprecated(bool):指示路由是否已弃用,用于自动生成API文档。
  6. methods(List[str]):允许的HTTP请求方法列表。默认为["GET"]。例如:methods=["GET", "POST"]。
  7. tags(List[str]):用于将路由分组到指定的标签中,用于自动生成API文档。例如:tags=["Users"]。
  8. dependencies(List[fastapi.Depends]):路由的依赖项列表,用于指定路由的依赖关系。例如:dependencies=[Depends(get_token)]。
  9. response_model(Type[BaseModel]):指定路由响应的模型类,用于自动生成API文档和进行数据验证。
  10. status_code(Dict[int, Dict[str, str]]):指定路由响应的状态码和对应的说明文本,用于自动生成API文档。例如:status_code={404: {"description": "Item not found"}}。
  11. response_description(str):路由响应的描述,用于自动生成API文档。
  12. response_model_exclude_unset(bool):指示在响应模型中排除未设置的字段,默认为False。
  13. response_model_exclude_defaults(bool):指示在响应模型中排除默认值的字段,默认为False。
  14. response_model_include(Union[SetIntStr, DictIntStrAny]):指定在响应模型中包含的字段列表或字典,用于自动生成API文档。例如:response_model_include={"name", "email"}。
  15. response_model_exclude(Union[SetIntStr, DictIntStrAny]):指定在响应模型中排除的字段列表或字典,用于自动生成API文档。例如:response_model_exclude={"password"}。
  16. response_model_by_alias(bool):指示是否根据响应模型的字段别名进行序列化,默认为True。
  17. response_model_exclude_unset(bool):指示在响应模型中排除未设置的字段,默认为False。
  18. response_model_exclude_defaults(bool):指示在响应模型中排除默认值的字段,默认为False。
  19. response_model_include(Union[SetIntStr, DictIntStrAny]):指定在响应模型中包含的字段列表或字典,用于自动生成API文档。例如:response_model_include={"name", "email"}。
  20. response_model_exclude(Union[SetIntStr, DictIntStrAny]):指定在响应模型中排除的字段列表或字典,用于自动生成API文档。例如:response_model_exclude={"password"}。
  21. response_model_by_alias(bool):指示是否根据响应模型的字段别名进行序列化,默认为True。
  22. include_in_schema(bool):指示是否将路由包含在自动生成的API文档中,默认为True。
  23. callbacks(Dict[str, Union[Callable, List[Callable]]]):指定在路由执行期间要调用的回调函数。

枚举参数​


整数参数验证​