5

In a function annotated as a hug api call, how can I get the headers for that call?

monty0
  • 1,759
  • 1
  • 14
  • 22

2 Answers2

4

The easy, normal and fastest way: Hug provides request and body (POST) if they are present as arguments (https://github.com/timothycrosley/hug/issues/120).

@hug.get('/headers', output=hug.output_format.json)
def headers(request, header_name: hug.types.text=None):
    if header_name is None:
        return request.headers
    return {header_name: request.get_header(header_name)}
danius
  • 2,664
  • 27
  • 33
3

Create a custom directive [1]:

@hug.directive()
def headers(request=None, **kwargs):
    """Returns the request"""
    return request and request.headers

To use it, prepend the magic hug_ prefix:

@hug.post('/sns/test')
def sns_test(hug_headers):
    message_type = 'X-AMZ-SNS-MESSAGE-TYPE'
    is_subscription = message_type in hug_headers \
                      and hug_headers[message_type] == 'SubscriptionConfirmation'
    return {'is_sub': is_subscription}
monty0
  • 1,759
  • 1
  • 14
  • 22
  • 1
    No need to create any directive for this, hug provides the request if present as parameter – danius Mar 02 '18 at 22:40
  • Thanks @danigosa. I had not been able to figure that out from the documentation but it makes perfect sense. – monty0 Mar 04 '18 at 00:24
  • One drawback from using hug is its poor documentation, it's not documented. Sometimes I think they spent more time in colors, css and images than putting code samples, I hope they improve this in the future – danius Mar 04 '18 at 00:39