How to return status code in response correctly?

Viewed 8224

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!

1 Answers

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',
    )
Related