FastAPI 请求参数及校验
Last updated
Last updated
alias #别名参数
title #标题
description #描述,会在借口文档有表述
特定的校验 min_length
max_length
regex
数值校验:
gt:大于(greater than)
ge:大于等于(greater than or equal)
lt:小于(less than)
le:小于等于(less than or equal)
注意:对于必需参数,我们没有顺序要求, 有默认值的参数必须放在没有默认值的后面
# coding: utf8
from fastapi import FastAPI
from typing import Optional
app = FastAPI()
# 请求参数, 有默认值
@app.get('/read1/')
async def
启动: uvicorn main:app --reload
# coding: utf8
from typing import Optional
from fastapi import FastAPI, Query
app = FastAPI()
# 请求参数 q,默认是 None, 可选
@app.get('/items/')
async def items(q: Optional[str] = None):
return {"q": q}
# 设置默认值为空,如果传参,必须是字符串, 正则校验, 长度校验, (都可单独)
# 如果必须传参: None => ... 设置三个点
# max_length=5, min_length=3 => 可写成 le=5,ge=3
@app.get('/items2/')
async def items(q: Optional[str] = Query(None, max_length=5, min_length=3, regex="^1")):
return {"q": q}
# 启动: uvicorn main:app --reload
# coding: utf8
from typing import Optional, List
from fastapi import FastAPI,Query
app = FastAPI()
@app.get('/items/')
async def items(q: Optional[List[str]] = Query(None)):
data = {}
if q:
data.update({'q': q})
return dat
http://10.11.9.247:8000/items/?q=a&q=b&q=c
{"q":["a","b","c"]}