FastAPI-带有PYDANIC列表字段的GET请求 [英] FastAPI - GET Request with Pydantic List field
本文介绍了FastAPI-带有PYDANIC列表字段的GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是FastAPI新手(从FlaskTM迁移),我正在尝试为我的GET路线创建一个PYDANIC模型
from fastapi import APIRouter,Depends
from pydantic import BaseModel
from typing import Optional,List
router = APIRouter()
class SortModel(BaseModel):
field: Optional[str]
directions: List[str]
@router.get("/pydanticmodel")
def get_sort(criteria: SortModel = Depends(SortModel)):
pass #my code for handling this route.....
当我运行curl -X GET http://localhost:XXXX/pydanticmodel?directions=up&directions=asc&field=id
时,收到422 Unprocessable Entity: {"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]}
directions:List[str]
-&>,我得到的是200 OK
方向=&<2-2]。
str
适用于查询参数而List[str]
不适用的原因是什么?我做错了什么?
谢谢。
推荐答案
目前还不能将带有PYDANIC LIST字段的GET请求用作查询参数。一旦您在模型中声明了一个列表字段,它就应该是主体参数,而不是查询参数(例如,您可以通过http://127.0.0.1:8000/docs的OpenAPI进行检查)。此外,由于您使用的是GET请求方法,因此即使您在正文中添加directions
的列表并尝试发送请求,它也不会起作用;因为该操作需要POST请求。
Query
,以便directions
可以在URL中多次出现,换句话说,就是接收多个值。
from typing import List, Optional
from fastapi import APIRouter, Depends, Query
router = APIRouter()
class SortModel:
def __init__(
self,
field: Optional[str],
directions: List[str] = Query(...)
):
self.field = field
self.directions = directions
@router.get("/")
def send_user(criteria: SortModel = Depends(SortModel)):
return criteria
这篇关于FastAPI-带有PYDANIC列表字段的GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文