Home > Back-end >  how can i manipulate my fastapi request headers to be mutable
how can i manipulate my fastapi request headers to be mutable

Time:11-12

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.

CodePudding user response:

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
     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'})
  • Related