FastApi process post arguments in url

Viewed 846

I'm building simple api using FastApi. Here is my POST request handler:

    @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'})

And testing this code works fine:

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]>

But when I try to pass arguments in urls it responses with code 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"}]}

Alternatevly if my post handler looks like this:

    @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'})

First request return 422 and second 200. How can I make both type of requests work fine?

If needed Resource model:

class Resource(BaseModel):
    title: str
    id: Optional[int] = -1
    amount: float
    unit: str
    price: float
    cost: Optional[float] = 0
    date: date
1 Answers
Related