Using FastAPI I am trying to add a header to the response.
For normal operations this works OK. Even if I raise HTTP Execeptions, I can provide a header.
But when something breaks big, no header is returned.
Update: Since I've received a few suggestions to how to replace the errors, let me clarify: I do not want to make any changes to the response AT ALL, also not to the exception, just add a header. The rest of the response should stay the same.
Example code.
from fastapi import FastAPI, HTTPException, Response
import uvicorn
app = FastAPI()
@app.get("/ok", include_in_schema=True)
def a(response: Response):
response.headers['myheader'] = '123456'
return {"status": "OK"}
@app.get("/fail", include_in_schema=True)
def b(response: Response):
raise HTTPException(401, 'Error', headers={'myheader': '123456'})
@app.get("/nok", include_in_schema=True)
def c(response: Response):
response.headers['myheader'] = '123456'
raise NotImplementedError("Let's see a header")
uvicorn.run(app=app, host="0.0.0.0", port=9999)
Here the first two endpoints return a header like
content-length: 15
content-type: application/json
date: Tue,21 Mar 2023 14:10:32 GMT
myheader: 123456
server: uvicorn
But the last one only has
content-length: 21
content-type: text/plain; charset=utf-8
date: Tue,21 Mar 2023 14:11:15 GMT
server: uvicorn
How do I add a "myheader" header to a breaking response like the last one?