I am trying to serve a Neural Network using FastAPI.
from fastapi import Depends, FastAPI from pydantic import BaseModel from typing import Dict class iRequest(BaseModel): arg1: str arg2: str class iResponse(BaseModel): pred: str probs: Dict[str, float] @app.post("/predict", response_model=iResponse) def predict(request: iRequest, model: Model = Depends(get_model)): pred, probs = model.predict(request.arg1, request.arg2) return iResponse(pred = pred, probs = probs)
The manual site http://localhost:8000/docs#/default/predict_predict_post works fine and translates into the following curl command:
curl -X POST "http://localhost:8000/predict" -H "accept: application/json" -H "Content-Type: application/json" -d "{"arg1":"I am the King","arg2":"You are not my King"}"
which also works. When I try to query the API using python requests:
import requests data = {"arg1": "I am the King", "arg2": "You are not my King"} r = requests.post("http://localhost:8000/predict", data=data)
I only get the “422 Unprocessable Entity” Errors. Where am I going wrong here?
Advertisement
Answer
You provide a data
argument to requests.post
, which does a POST with Content-Type: application/x-www-form-urlencoded
, which is not JSON.
Consider using requests.post(url, json=data)
and you should be fine.