FastAPI: Cannot get error handling to work as expected

Viewed 2445

I am just learning FastAPI (and loving it), so it is quite likely I am doing something wrong. But here is my problem:

In the code snippet below, I am creating a new user, if there is no user already.

The code works fine, but it is the error handling that I am having trouble with. The errors are properly being pushed forward to FastAPI's internal docs or to an API client like Postman, but not back to the actual client that I am using or the command line.

@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = crud.get_user_by_username(db, username=user.username)
    if db_user:
        raise HTTPException(
            status_code=400, detail=f"Username '{user.username}' already registered"
        )
    return crud.create_user(db=db, user=user)

If I use the auto-generated FastAPI docs (or Postman) and monitor the response in that way, I get the error I am expecting:

Proper error response in API docs

But when I look at what I am receiving at the client end (Vue) or what the uvicorn server is logging, it does not contain that information:

Incorrect error response being logged

As you can see, it just says Bad Request instead of responding with the JSON dict of {"detail": "Username 'miketest' already registered"}


What am I doing wrong? What can I do to make sure that the full HTTPException information is being returned? I am pretty sure the problem is on the FastAPI end, because the client is receiving exactly what the server is outputting as well.

2 Answers

I figured out the problem, and it was not a FastAPI issue, per se, but it was on how it passes information back to the front end.

I thought I should keep this question in case someone has the same issue.


Solution:

    try {
      await api().post('register',JSON.stringify(data);
    } catch (err) {
      error = err.response.data.detail;
    }

That is to say, the error sent from FastAPI is an object that has a response, and in it a data, and in that a detail.

The response from Postman or anything similar just gives an object with detail. I did not see that there was a middle data layer, and I was having trouble seeing the entire object from within Vue.

This screenshot belongs to console log and it will not contain the API response, the JSON response.

You can see the actual response if you send the request the API using some client, like POSTMAN.

Related