Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

utility functions for API examples

Project: API Tutorial
Views: 262
Kernel: Python 3 (system-wide)
import requests from requests.auth import HTTPBasicAuth import json import yaml import os import pprint
pp = pprint.PrettyPrinter()
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()
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