How to customise error response for a specific route in FastAPI?

Option 1 If you didn’t mind having the Header showing as Optional in OpenAPI/Swagger UI autodocs, it would be as easy as follows: from fastapi import Header, HTTPException @app.post(“/”) def some_route(some_custom_header: Optional[str] = Header(None)): if not some_custom_header: raise HTTPException(status_code=401, detail=”Unauthorized”) return {“some-custom-header”: some_custom_header} Option 2 However, since you would like the Header to appear as … Read more

How to use a Pydantic model with Form data in FastAPI?

I found a solution that can help us to use Pydantic with FastAPI forms 🙂 My code: class AnyForm(BaseModel): any_param: str any_other_param: int = 1 @classmethod def as_form( cls, any_param: str = Form(…), any_other_param: int = Form(1) ) -> AnyForm: return cls(any_param=any_param, any_other_param=any_other_param) @router.post(”) async def any_view(form_data: AnyForm = Depends(AnyForm.as_form)): … It’s shown in the … Read more

How to exclude Optional unset values from a Pydantic model using FastAPI?

You can use exclude_none param of Pydantic’s model.dict(…): class Text(BaseModel): id: str text: str = None class TextsRequest(BaseModel): data: list[Text] n_processes: Optional[int] request = TextsRequest(**{“data”: [{“id”: “1”, “text”: “The text 1”}]}) print(request.dict(exclude_none=True)) Output: {‘data’: [{‘id’: ‘1’, ‘text’: ‘The text 1′}]} Also, it’s more idiomatic to write Optional[int] instead of Union[int, None].

How to download a large file using FastAPI?

If you find yield from f being rather slow when using StreamingResponse with file-like objects, for instance: from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path=”large-video-file.mp4″ app = FastAPI() @app.get(“https://stackoverflow.com/”) def main(): def iterfile(): with open(some_file_path, mode=”rb”) as f: yield from f return StreamingResponse(iterfile(), media_type=”video/mp4″) you could instead create a generator where you read the … Read more

How to return a custom Response when a Header is absent from the Request using FastAPI?

Option 1 If you didn’t mind having the Header showing as Optional in OpenAPI/Swagger UI autodocs, it would be as easy as follows: from fastapi import Header, HTTPException @app.post(“/”) def some_route(some_custom_header: Optional[str] = Header(None)): if not some_custom_header: raise HTTPException(status_code=401, detail=”Unauthorized”) return {“some-custom-header”: some_custom_header} Option 2 However, since you would like the Header to appear as … Read more

How to add both file and JSON body in a FastAPI POST request?

As per FastAPI documentation, You can declare multiple Form parameters in a path operation, but you can’t also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using application/x-www-form-urlencoded instead of application/json (when the form includes files, it is encoded as multipart/form-data). This is not a … Read more