How to build an API connection in Python

This article shows an example of an API connection in Python. We provide additional and more in-depth information on https://mopinion-python-api.readthedocs.io/en/latest/.

Code

In the below code replace the following with your own credentials.

public_key = '8e8e8e8e8e88e'
token = '9d9galnojvavlkre455%lreagfglkfgslkng'

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import requests import base64 import hmac, hashlib import simplejson as json import pprint pp = pprint.PrettyPrinter(indent=1) def callAPI(base_url, public_key, token, endpoint='/account', method='GET', body='', query=''): signature_token = bytes(token.encode('utf-8')) uri_and_body = '{}|{}'.format(endpoint,body).encode('utf-8') uri_and_body_hmac_sha256 = hmac.new(signature_token, msg=uri_and_body, digestmod = hashlib.sha256).hexdigest() xtoken = base64.b64encode(bytes('{}:{}'.format(public_key, uri_and_body_hmac_sha256), 'utf-8')) url = '{}{}{}'.format(base_url, endpoint, query) headers = { 'X-Auth-Token': xtoken, 'version':'1.18.14', 'verbosity':'full' } response = requests.request(method, url, data=body, headers=headers, params=query) return response, xtoken baseurl = 'https://api.mopinion.com' endpoint = '/account' #public key and signature token public_key = '8e8e8e8e8e88e' token = '9d9galnojvavlkre455%lreagfglkfgslkng' query = '' call = callAPI(baseurl,public_key,token,endpoint,query=query) pp.pprint(call[0].json()) print(call[1])