2

I have the following FastAPI code:

@app.post('/api_name')
async def api_func(HMAC: str = Header(...)):
try:
return 'success'
except Exception as err:
return err

The issue is that when I do not add HMAC in header, it gives error response

{
    "detail": [
        {
            "loc": [
                "header",
                "HMAC"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

I want to customise this error response like,

{
"Success": false,
"Error": "HMAC is required in Header"
}

I also tried different code but still it gives same error response

@app.post('/api_name')
async def api_func(HMAC: str = Header(...)):
    try:
        return 'success'

    except HTTPException as err:
        if err.status_code == 422 and 'HMAC' in err.detail[0]['loc']:
            return {'Success': False, 'Error': 'HMAC is required in Header'}
        else:
            raise err
Adi
  • 19
  • 3
  • 1
    [This section](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) of the fastapi doc might answer your quetsion – Seon Feb 20 '23 at 09:57
  • Does this answer your question? [How to return a custom 404 Not Found page using FastAPI?](https://stackoverflow.com/questions/71800133/how-to-return-a-custom-404-not-found-page-using-fastapi) – Chris Feb 20 '23 at 11:58
  • 1
    Related answers can also be found [here](https://stackoverflow.com/a/70954531/17865804), as well as [here](https://stackoverflow.com/a/73283272/17865804) and [here](https://stackoverflow.com/a/71682274/17865804) – Chris Feb 20 '23 at 11:59

0 Answers0