【发布时间】:2021-04-16 10:22:17
【问题描述】:
我正在使用 FastApi 构建简单的 api。这是我的 POST 请求处理程序:
@resources_router.post('', tags=['resources'])
async def post_resources(request: Resource): // where Resource is a Pydantic model
resource = parse_obj_as(Resource, request)
...
...
return resource.dict(exclude={'id', 'cost'})
并且测试此代码工作正常:
res1 = requests.post('http://0.0.0.0:8080/resources',
json.dumps({'title': 'good', 'amount': 1234, 'unit': 'gram', 'price': 12, 'date': '2007-07-07'}))
//Returns <Response [200]>
但是当我尝试在 url 中传递参数时,它会以代码 422 响应
res2 = requests.post(url='http://0.0.0.0:8080/resources?title=good&amount=1234&unit=gram&price=12&date=2007-07-07')
// Returns <Response [422]>
{"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]}
如果我的帖子处理程序如下所示:
@resources_router.post('', tags=['resources'])
async def post_resources_params(title: str, amount: float, unit: str, price: float, date: datetime.date):
resource = Resource(title=title,amount=amount,unit=unit,price=price,date=date)
...
...
return resource.dict(exclude={'id', 'cost'})
第一个请求返回 422,第二个请求返回 200。 如何使这两种类型的请求都能正常工作?
如果需要资源模型:
class Resource(BaseModel):
title: str
id: Optional[int] = -1
amount: float
unit: str
price: float
cost: Optional[float] = 0
date: date
【问题讨论】:
标签: url post python-requests fastapi pydantic