I am trying to serve a Neural Network using FastAPI.
JavaScript
x
17
17
1
from fastapi import Depends, FastAPI
2
from pydantic import BaseModel
3
from typing import Dict
4
5
class iRequest(BaseModel):
6
arg1: str
7
arg2: str
8
9
class iResponse(BaseModel):
10
pred: str
11
probs: Dict[str, float]
12
13
@app.post("/predict", response_model=iResponse)
14
def predict(request: iRequest, model: Model = Depends(get_model)):
15
pred, probs = model.predict(request.arg1, request.arg2)
16
return iResponse(pred = pred, probs = probs)
17
The manual site http://localhost:8000/docs#/default/predict_predict_post works fine and translates into the following curl command:
JavaScript
1
2
1
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"}"
2
which also works. When I try to query the API using python requests:
JavaScript
1
5
1
import requests
2
data = {"arg1": "I am the King",
3
"arg2": "You are not my King"}
4
r = requests.post("http://localhost:8000/predict", data=data)
5
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.