Home > Enterprise >  How to POST a single parameter as JSON in FastAPI?
How to POST a single parameter as JSON in FastAPI?

Time:07-24

I have a working model using transformers pipeline and I want to use it with FastAPI to send post requisitions and get the response.

The model works this way:

#Loading the model
classifier = pipeline(path_to_model)

#Making predictions:
classifier(txt)

The output is a list of dicts.

My code is:

app = FastAPI()

@app.post("/predictions")
def extract_predictions(text):
    text = text.lower()
    out=classifier(text)
    return {
            "text_message": text, 
            "predictions": out
           }

I can get predictions if I use localhost:8000/docs, but when I use postman or insominia and body(JSON) {"text":"any string"} I get "field_required"

The model takes a string as an input and my postman request uses a JSON body. How can I update model to get the input as JSON?

CodePudding user response:

The text attribute, as is currently defined, is expected to be a query parameter, not body (JSON) parameter. Hence, you can either send it as a query parameter when POSTing your request, or define it using Body field (e.g., text: str = Body(..., embed=True)), so that is expected in the body of the request as JSON. Please have a look at the answers here and here for more details.

  • Related