How to return status code in response correctly?
Asked Answered
H

1

17

So I am learning FastAPI and I am trying to figure out how to return the status code correctly. I made an endpoint for uploading a file and I want to make a special response in case the file format is unsupported. It seems like I did everything according to the official documentation, but I am always getting 422 Unprocessable Entity error.

Here's my code:

from fastapi import FastAPI, File, UploadFile, status
from fastapi.openapi.models import Response
    
app = FastAPI()
    
@app.post('/upload_file/', status_code=status.HTTP_200_OK)
async def upload_file(response: Response, file: UploadFile = File(...)):
    """End point for uploading a file"""
    if file.content_type != "application/pdf":
        response.status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
        return {f'File {file.filename} has unsupported extension type'}

    return {'filename': file.content_type}

Thank you in advance!

Hearty answered 6/7, 2021 at 12:12 Comment(0)
I
21

When you receive a 422 response, it means that Pydantic's validators perceived an error in the parameters you sent to your endpoint. (in the majority of cases)

To return an error, instead of using Response, I encourage you to use HTTPException in the following manner:

from fastapi import status, HTTPException

...

if file.content_type != "application/pdf":
    raise HTTPException(
        status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
        detail=f'File {file.filename} has unsupported extension type',
    )
Inotropic answered 6/7, 2021 at 12:59 Comment(2)
How can I serialize the status code when using HTTPException?. It only shows the detailAcetaldehyde
In the example above, the status_code argument to HTTPException is there to do that. The response will contain an HTTP header that specifies the status code associated with the response.Inotropic

© 2022 - 2024 — McMap. All rights reserved.