0

I am trying to reach a fastAPI endpoint using the python requests, however, any request always returns a 422 Unprocessable Entity error. I have looked at other similar posts, such as this one, but to no avail. No matter if I send the request_dict as data, json, or params, I get the same error.

Here is where I define my FastAPI endpoint:

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_methods=['*'],
    allow_headers=['*']
)

class ModelInterface(BaseModel):
    name: str
    contents: str
    languages: List[str]

@app.post("my_endpoint")
async def determine_file(model: ModelInterface) -> Dict[str,str]:
    name = model.name
    contents = model.contents
    languages = model.languages
    <logic here>

And here is what tries to request this endpoint:

def call_filedet(name: str, contents: str, languages: str) -> Dict[str, str]:
    
    url = "http://my_url/my_endpoint"
    
    request_dict = {
        "name": name,
        "contents": contents,
        "languages": languages
    }

    response = requests.post(url, params=request_dict)

Does anyone know what the issue may be? I'm pretty stuck and don't know how to debug because the only response I get is the 422 error message.

JasonFitz
  • 183
  • 1
  • 11
  • 1
    On the console where you're running the python webserver (normally `uvicorn`) you should get a log which will provide useful information. Can you share it? – lsabi Jul 20 '23 at 20:13
  • If you print `response.json()` it will tell you what validation has failed. In this case, I suspect it's that you have `languages: List[str]` in your endpoint, but `languages: str` in your client. Also, you should send your `request_dict` with the `json` argument (`response = requests.post(url, json=request_dict)`). – M.O. Jul 20 '23 at 20:50
  • In addition to the link above, you might find [this answer](https://stackoverflow.com/a/71439821/17865804) and [this answer](https://stackoverflow.com/a/75998823/17865804) helpful as well – Chris Jul 21 '23 at 04:20

0 Answers0