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?

1 Answer 1

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(...)):
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

It's also well explained in the docs. I guess OP didn't go through the docs first... fastapi.tiangolo.com/tutorial/body-multiple-params/…
How should I send a query parameter?
Check my another answer to see the difference between them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.