FastAPI: 请求查询参数的校验(4)

可以通过Query来实现对字符串查询参数的校验。

常规校验

1
2
3
4
5
6
7
8
books = [{'name': 'python'}, {'name': 'fastapi'}, {'name': 'java'}]

@app.get('/books/')
def root(book: str = Query('Java Script', min_length=2)):

if book:
books.append({'name': book})
return books

参数的默认值是Java Script,最小长度是2。

1
2
3
4
5
http://127.0.0.1:8000/books/
[{"name":"python"},{"name":"fastapi"},{"name":"java"},{"name":"Java Script"}]

http://127.0.0.1:8000/books/?book=c
{"detail":[{"loc":["query","book"],"msg":"ensure this value has at least 2 characters","type":"value_error.any_str.min_length","ctx":{"limit_value":2}}]}

甚至可以直接用正则表达式来做检验,一般应该也用不到。

1
2
3
4
5
6
@app.get('/books/')
def root(book: Optional[str] = Query('Java Script', min_length=2, regex='^J')):

if book:
books.append({'name': book})
return books

必填参数

可以将 ... 用作第一个参数值,在声明必填参数。

1
2
3
4
5
6
@app.get('/books/')
def root(book: str = Query(..., min_length=2, regex='^J')):

if book:
books.append({'name': book})
return books

参数列表多个值

查询参数可以声明时接受多个值

1
2
3
4
5
6
7
8
books = ['python', 'fastapi']

@app.get('/books/')
def root(book: Optional[list] = Query(None)):

if book:
books.extend(book)
return books

结果

1
2
3
4
5
http://127.0.0.1:8000/books/
["python","fastapi"]

http://127.0.0.1:8000/books/?book=java&book=c
["python","fastapi","java","c"]

还有下面的校验,用到再说

  • alia
  • title
  • description
  • deprecated
唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!