CoCalc Public FilesPublic / PYTHON / 01-utils.ipynbOpen with one click!
Author: ℏal Snyder
Description: API tutorial part 1
Compute Environment: Ubuntu 18.04 (Deprecated)
In [1]:
import requests from requests.auth import HTTPBasicAuth import json import yaml import os import pprint
In [2]:
pp = pprint.PrettyPrinter()
In [3]:
def get_api_key(fname=os.path.expanduser("~/SECRET/testuser.yaml")): r""" input file: api_key: sk_... returns dict of user info settings """ with open(fname,"r") as inf: api_key = yaml.safe_load(inf)['api_key'] return api_key api_key = get_api_key()
In [ ]:
def call_api(msg, payload={}, sk=api_key, base_url="https://cocalc.com", max_retries=3, timeout=4): r""" generic API call with retries msg - string message type: "create_account", "create_project", etc. payload - dict of parameters for the call sk - string, security key retries - int, number of retries on post return python dict of API response object """ s = requests.Session() a = requests.adapters.HTTPAdapter(max_retries=max_retries) s.mount('https://', a) url = "{}/api/v1/{}".format(base_url, msg) auth = HTTPBasicAuth(sk,'') headers = {'content-type': 'application/json'} r = s.post(url,auth=auth,data=json.dumps(payload),headers=headers, timeout=timeout) assert r.status_code == requests.codes.ok,"bad status code {}".format(r.status_code) retval = r.json() return retval
In [ ]: