2

I have a fast api for a simple ML model. THE post request for API is

@app.post('/predict')   
def predict_species(data: str):
    data_new = np.array([data])

    prob = lr_tfidf.predict_proba(data_new).max()
    pred = lr_tfidf.predict(data_new)
    return {'Movie Review': data,
             'Predictions':f'{pred[0]}',
            'Surity for Review': f'{prob}'}

Now, when I try to connect it using python requests module, it is giving me error.

import requests

review = {'data': 'THIS IS A POSITIVE MOVIE'}
resp = requests.post("http://localhost:8000/predict", json=review)   

print(resp.content)

The content is

b'{"detail":[{"loc":["query","data"],"msg":"field required","type":"value_error.missing"}]}'

The Terminal Error Message is

INFO:     127.0.0.1:45730 - "POST /predict HTTP/1.1" 422 Unprocessable Entity

How to solve this?

Ahmad Anis
  • 2,322
  • 4
  • 25
  • 54

1 Answers1

1

FastAPI expects a query parameter like this, but you are sending a json in the request's body.

This expects a query parameter

@app.post('/predict')   
def predict_species(data: str):

You need to use Body() function or a Pydantic model.

from fastapi import Body

@app.post('/predict')   
def predict_species(data: str = Body(...)):
    ...
Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85