A Small FastAPI + Axios Gotcha Behind That 422 Error

Published:

When I first started playing with FastAPI for a small side project, I ran into a confusing issue: a POST request sent from a React frontend with axios kept returning a 422 error.

In FastAPI, a 422 response usually means the data being sent in the request does not match what the backend expects to receive. At first glance, the backend code looked perfectly fine—there was only a single pid field:

@router.post('/paper/like')
def like(pid: int):
    res = paper.like(pid)
    if res >= 1:
        return {'message': 'success'}
    else:
        return {'message': 'failed'}

Nothing about that seems obviously wrong, which is why this took a while to figure out. The real issue turned out to be FastAPI's request validation behavior. Once the request body was defined with a Pydantic model, FastAPI was able to parse the axios request normally.

class LikePaper(BaseModel):
    pid: int

@router.post('/paper/like')
def like(item: LikePaper):
    res = paper.like(item)
    if res >= 1:
        return {'message': 'success'}
    else:
        return {'message': 'failed'}

After changing the endpoint to use a Pydantic model, the request worked as expected.

axios request failed

The difference was also easy to see in practice: the axios request failed, while the same endpoint could be called successfully from FastAPI's built-in docs.

FastAPI docs request works