422 Unprocessable Entity in fastapi when returning response

Viewed 124

I am using fast API to do machine learning inference and return response. There are two tasks that are controlled by task_id. For task_id=0 both solvent and solute are required to return response when using task_id=1 I only need solute. But when giving the values for the keys it is required to give solvent value in task_id=1 where I don't need it. If not given the value I am getting 422 Unprocessable Entity. Is their a way to write so that it wont throw the error if solvent value is not provided when using task_id=1

@app.get('/predict')
async def predict(task_id:int, background_tasks: BackgroundTasks,solute,solvent):
    global task_id_global
    task_id_global = task_id
    if task_id == 0:
        background_tasks.add_task(predictions,solute,solvent)
        return {'success'}
    elif task_id == 1:
        # solvent = None
        background_tasks.add_task(predictions_two,solute)
        return {'success'}
    else:
        return "Give proper task_id"
1 Answers

Declare your parameter as Optional. For instance:

from typing import Optional
...
async def predict(solvent: Optional[str] = None):
...
Related