Follow

Sample Python Script: Generate Signature

This code shows an example of how to generate a signature for API requests. The $token, $username, and data parameter array values must be passed to the script.

"""Python example of generating Angelfish API signatures."""

import hmac
import hashlib
import base64


def sign_data(data, token):
    """Signs data for an Angelfish API request."""

    # sort and concatenate the parameters
    data_str = ''.join(
        [key + '=' + val for key, val in sorted(data.items())])

    # generate an hmac md5 digest of the data string
    digest = hmac.new(str(token), str(data_str), hashlib.md5).digest()

    # base64 encode the digest and strip any trailing whitespace or '='
    b64_digest = base64.encodestring(digest).strip().rstrip('=')
    print b64_digest

    return b64_digest


if __name__ == '__main__':
    # the token provided by angelfish during authentication
    TOKEN = 'TOKEN'

    # the angelfish username that requested the token
    USERNAME = 'USERNAME'

    # the post data with username added
    DATA = {'ids': '1',
            'start-time': '20100101',
            'end-time': '20170131',
            'format': 'csv',
            'dimensions': 'source',
            'metrics': 'visits',
            'username': USERNAME}

    # generate the signature and add it to the post data
    DATA['signature'] = sign_data(DATA, TOKEN)
Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

0 Comments

Article is closed for comments.