Search code examples
pythonfastapipydantic

Why am I getting FastAPI value_error.missing?


I am building a FastAPI app that takes in a sentence and returns the emotion classification of the sentence based on the prediction of a huggingFace model.

Here is my code in model.py file :

def changeDict(input):
   new_dict = {item['label']: item for item in input}
   return new_dict

def predict_pipeline(text):
   text = re.sub(r'[!@#$(),\n"%^*?\:;~`0-9]', " ", text)
   #text = re.sub(r"[[]]", " ", text)
   text = text.lower()
   prediction = changeDict(classifier(text)[0])
   #print(text)
   #print(prediction)
   return(prediction)

Here is the code with my post route in my main.py file:

app = FastAPI()

class textIn(BaseModel):
  sentence: str 

class PredictionOut(BaseModel):
  Emotion: dict

@app.get("/")
def home():
   return {"health check": "OKAY"}

@app.post("/predict/", response_model=PredictionOut)
async def predict(PayLoad: textIn):
   emotion = predict_pipeline(PayLoad.sentence)
   return {"emotion": emotion}

When I test this out, I get the following error. Can some one help me understand why?

pydantic.error_wrappers.ValidationError: 1 validation error for PredictionOut
response -> Emotion
 field required (type=value_error.missing)

Solution

  • Your class PredictionOut want "Emotion", but the predict function return {"emotion": emotion}. Pydantic is strictly case sensitive. Try:

    @app.post("/predict/", response_model=PredictionOut)
    async def predict(PayLoad: textIn):
       emotion = predict_pipeline(PayLoad.sentence)
       return {"Emotion": emotion}