Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return status code in response correctly?

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!

like image 473
Vlad Vlad Avatar asked Dec 03 '25 22:12

Vlad Vlad


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',
    )
like image 87
fchancel Avatar answered Dec 06 '25 17:12

fchancel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!