'Request add header before sending

I want to add a parameter to the header of my request before sending it without adding it manually every time. For example, if I have a fast api project, I can create a middleware. This middleware will be executed directly after a request comes in and before the mapped function is called. Does someone know how to have something like that for outgoing requests with the requests library?



Solution 1:[1]

Just create your own function that calls requests and adds whatever header(s) you want added every time:

import requests

def post(url, json):
    headers = {'My Header': 'Lorem ipsum dolor sit amet'}
    return requests.post(url=url, headers=headers, json=json)

post(url="www.google.de", json={"name":"Gerry"})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kurt