aserrin55
aserrin55

Reputation: 360

FastAPI Python no value in the POST petition

I have a function for FastAPI defined as:

@app.post("/rating")
def read_prediction(id: int, team: int, location: float, age: float):

The problem starts when I received a POST petition in which there is no value for one of the predefined parameters, as follows:

*"POST /rating?id=27691&team=1673&location=328&age= HTTP/1.1" 422*

With this request, it does not enter the function. I have tried different options, for example introduce a default value, but it does not work.

@app.post("/rating")
def read_prediction(id: int, team: int, location: float, age: float = 26.5):

Also with Optional

from typing import Optional
def read_prediction(id: int, team: int, location: float, age: Optional[float] = 26.5):

But I am not able to handle this exception. When the POST petition includes the age, the function works as expected.

Another solution that I have been thinking in, is to define multiple functions without the parameters that can be empty, but i don't know if it is the best way to solve it.

Upvotes: 1

Views: 1061

Answers (2)

Reniz Shah
Reniz Shah

Reputation: 36

Just remove &age= from your URL. If that is not possible, then remove data type from your FastAPI code:

@app.post("/rating")
def read_prediction(id: int, team: int, location: float, age):

If you really want to apply data types, then create model and accept data as request body with all the validations.

Upvotes: 0

yogesh
yogesh

Reputation: 148

Even though your intent is to post, it will work if you change post to get but it will not be meaningfull. Again since your intent is to post you should be using Models as given here or add body for each parameter if you want it in request body or Query if you want it in query parameter or even both!

from fastapi import Path, Body, Query

@app.post("/rating")
def read_prediction(id: int = Query(...), age: float = Body(None)):
    """
    ... -> mandatory or None for optional
    """

adding default(26.5 or any other value) is not good in fn parameter itself, instead do it inside fn as required

Upvotes: 1

Related Questions