FastAPI学习-参数校验

GET操作不能使用RequestBody,POST/PUT/DELETE/PATCH可以。

Query参数校验

Query参数除了可以进行基本的类型校验,如是否为int或str外,还可以进行其他自定义校验,但需要引入Query

设置参数是否可选及默认值

可选参数: 使用Query(None)

默认值: 使用Query(“defaultvalue”)

必填参数: 使用Query(…)

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = Query(..., min_length=3)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

字符串长度限制

字符串长度限制: 使用Query(min_length=3, max_length=50)

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = Query(None, min_length=3, max_length=50)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

正则匹配

使用Query(…, regex="^fixedquery$")

  1. 将客户端的request解析为JSON
  2. 将request参数转换为相应的数据类型
  3. 校验数据类型,如果错误返回提示信息
  4. 将request传入相应方法
  5. 数据模型可以复用,并在交互式文档内显示
  6. 编辑器可以根据模型进行类型提示

参数使用列表时

参数为列表时需要用Query,否则会被识别为RequestBody

from typing import List

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: List[str] = Query(None)):
    query_items = {"q": q}
    return query_items
from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: list = Query(None)):
    query_items = {"q": q}
    return query_items

http://localhost:8000/items/?q=foo&q=bar 的Query参数会被解析为
{
“q”: [
“foo”,
“bar”
]
}

可以使用以下方法设置默认值

from typing import List

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: List[str] = Query(["foo", "bar"])):
    query_items = {"q": q}
    return query_items

Query其他参数设置

title: 参数名

description: 参数描述

alias: 同义词

deprecated: 当前版本是否可用

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(
    q: str = Query(
        None,
        title="Query string",
        description="Query string for the items to search in the database that have a good match",
        alias="item-query",
        deprecated=True,
    )
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

Path参数校验

Query参数的设置在Path中都可以用,只是要引入Path

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Path参数还可以进行数字校验,如大于(gt)、小于(lt)、大于等于(ge)、小于等于(le)

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Path参数还可以进行float校验

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(..., gt=0, lt=10.5)
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

参考资料

  1. FastAPI官网 :https://fastapi.tiangolo.com/
  2. FastAPI源码 :https://github.com/tiangolo/fastapi

你可能感兴趣的:(后端开发)