5

I am trying to change my request headers in my api code. Its immutable right now oob with fastapi starlette. how can i change it so my request headers are mutable? i would like to add, remove, and delete request headers. i tried to instantiate a new request and directly modify the request using

request.headers["authorization"] = "XXXXXX"

but I get the following error

TypeError: ‘Headers’ object does not support item assignment

Thanks!

Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
vee
  • 680
  • 1
  • 10
  • 27

1 Answers1

8

I'm assuming you want to do something with the header in a middleware. Because FastAPI is Starlette underneath, Starlette has a data structure where the headers can be modified. You can instantiate MutableHeaders with the original header values, modify it, and then set request._headers to the new mutable one. Here is an example below:

from starlette.datastructures import MutableHeaders
from fastapi import Request    

@router.get("/test")
def test(request: Request):
     new_header = MutableHeaders(request._headers)
     new_header["xxxxx"]="XXXXX"
     request._headers = new_header
     request.scope.update(headers=request.headers.raw)
     print(request.headers)
     return {}

Now you should see "xxxxx" is in the print output of your request.headers object:

MutableHeaders({'host': '127.0.0.1:8001', 'user-agent': 'insomnia/2021.5.3', 'content-type': 'application/json', 'authorization': '', 'accept': '*/*', 'content-length': '633', 'xxxxx': 'XXXXX'})
Himel Das
  • 1,148
  • 10
  • 13
  • 5
    It might be added that this will not update the scope attribute of the Request-object. For that to happen the update member function has to be called `request.scope.update(headers=request.headers.raw)` – F. Sonntag Feb 28 '22 at 07:55
  • 2
    The above response is useless without your suggestion for the ```scope``` update. Thank you! – elano7 Oct 13 '22 at 22:44
  • 3
    This doesn't Work. – supersick Oct 30 '22 at 05:09
  • 1
    Really, author, please, consider adding the @F.Sonntag suggestion to the answer, otherwise it doesn't work... – Frankie Drake Jun 26 '23 at 13:56