Skip to content

Adding custom HTTP headers to requests

Renato Byrro edited this page Feb 16, 2021 · 3 revisions

AsyncHttpHandler Class takes an argument called custom_headers, which accepts a function (or another Callable) that returns a Dict[str, str] object. This dictionary is appended to the default HTTP headers sent with log messages to the host.

Setting custom headers can be useful when you need to submit dynamic information on each request.

As an example, consider you need to add an authorization token in log messages, in order to validate the sender. The token will vary according to who is logged in your app.

Here's how you could do this:

def get_user_auth_token():
    # Implement your logic here...
    pass

def auth_header():
    return {
        'Authorization': f'Bearer: {get_user_auth_token()}',
    }

handler = AsyncHttpHandler(
    host='my-domain.com',
    custom_headers=auth_header,
)

It was implemented as a Callable to give enough flexibility to customize the HTTP headers throughout the execution of your program, in case it's needed.

If you need to always send the same dictionary, use a lambda:

handler = AsyncHttpHandler(
    host='my-domain.com',
    custom_headers=lambda: {'foo': 'bar'},
)

Another way to accomplish the same (passing in custom information to the host in log message requests) is by adding an extra argument to log messages[extra arg]:

logger.info('Some information', extra={'Authorization': 'token'})

The drawback is that the data needs to be inserted in each and every log message. The custom_headers facility, on the other hand, allows to set only once when the AsyncHttpHandler is instantiated.


Footnotes

[extra arg] Refer to Logging extra fields in the documentation

Clone this wiki locally