Files

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

194 lines
5.3 KiB
Python
Raw Permalink Normal View History

"""
Common methods used by the API sample scripts.
"""
2016-02-18 12:54:29 +00:00
import json
import logging
import sys
2020-10-06 18:49:19 +01:00
from urllib.error import HTTPError
from urllib.request import (
Request,
urlopen,
)
2010-10-26 10:00:23 -04:00
2017-08-17 00:33:02 +01:00
log = logging.getLogger(__name__)
2017-08-17 00:33:02 +01:00
def make_url(api_key, url, args=None):
"""
Adds the API Key to the URL if it's not already there.
"""
if args is None:
args = []
argsep = "&"
if "?" not in url:
argsep = "?"
if "?key=" not in url and "&key=" not in url:
2017-08-17 00:33:02 +01:00
args.insert(0, ("key", api_key))
2020-01-23 09:55:11 +00:00
return url + argsep + "&".join("=".join(t) for t in args)
2017-08-17 00:33:02 +01:00
def get(api_key, url):
"""
Do the actual GET.
"""
2017-08-17 00:33:02 +01:00
url = make_url(api_key, url)
try:
2017-08-17 00:33:02 +01:00
return json.loads(urlopen(url).read())
2016-02-18 12:54:29 +00:00
except ValueError as e:
2024-04-27 16:03:22 +01:00
print(f"URL did not return JSON data: {e}")
sys.exit(1)
2017-08-17 00:33:02 +01:00
def post(api_key, url, data):
"""
Do the actual POST.
"""
2017-08-17 00:33:02 +01:00
url = make_url(api_key, url)
req = Request(url, headers={"Content-Type": "application/json"}, data=json.dumps(data))
return json.loads(urlopen(req).read())
2017-08-17 00:33:02 +01:00
def put(api_key, url, data):
"""
Do the actual PUT
"""
2017-08-17 00:33:02 +01:00
url = make_url(api_key, url)
req = Request(url, headers={"Content-Type": "application/json"}, data=json.dumps(data))
2010-10-26 10:00:23 -04:00
req.get_method = lambda: "PUT"
2017-08-17 00:33:02 +01:00
return json.loads(urlopen(req).read())
2010-10-26 10:00:23 -04:00
2017-08-17 00:33:02 +01:00
def __del(api_key, url, data):
"""
Do the actual DELETE
"""
2017-08-17 00:33:02 +01:00
url = make_url(api_key, url)
req = Request(url, headers={"Content-Type": "application/json"}, data=json.dumps(data))
2010-11-07 22:18:22 -05:00
req.get_method = lambda: "DELETE"
2017-08-17 00:33:02 +01:00
return json.loads(urlopen(req).read())
2010-11-07 22:18:22 -05:00
2010-10-26 10:00:23 -04:00
2017-08-17 00:33:02 +01:00
def display(api_key, url, return_formatted=True):
"""
Sends an API GET request and acts as a generic formatter for the JSON response.
"""
try:
2017-08-17 00:33:02 +01:00
r = get(api_key, url)
2016-02-18 12:54:29 +00:00
except HTTPError as e:
print(e)
2017-08-17 00:33:02 +01:00
print(e.read(1024)) # Only return the first 1K of errors.
sys.exit(1)
2010-10-26 10:00:23 -04:00
if not return_formatted:
return r
2023-09-20 01:43:40 +01:00
elif isinstance(r, list):
# Response is a collection as defined in the REST style.
2016-02-18 12:54:29 +00:00
print("Collection Members")
print("------------------")
for n, i in enumerate(r):
2021-01-20 22:17:00 -05:00
if isinstance(i, str):
2024-04-27 16:03:22 +01:00
print(f" {i}")
2021-01-20 22:17:00 -05:00
else:
# All collection members should have a name in the response.
# url is optional
if "url" in i:
2024-11-24 21:35:20 +00:00
print("#{}: {}".format(n + 1, i.pop("url")))
2021-01-20 22:17:00 -05:00
if "name" in i:
2024-04-27 16:03:22 +01:00
print(f" name: {i.pop('name')}")
2021-02-02 16:01:17 -05:00
try:
for k, v in i.items():
2021-10-24 12:10:30 +01:00
print(f" {k}: {v}")
2021-02-02 16:01:17 -05:00
except AttributeError:
for item in i:
print(item)
2016-02-18 12:54:29 +00:00
print("")
2024-11-24 21:35:20 +00:00
print(f"{len(r)} element(s) in collection")
2023-09-20 01:43:40 +01:00
elif isinstance(r, dict):
# Response is an element as defined in the REST style.
2016-02-18 12:54:29 +00:00
print("Member Information")
print("------------------")
for k, v in r.items():
2020-10-06 18:49:19 +01:00
print(f"{k}: {v}")
2023-08-09 16:50:10 +02:00
elif isinstance(r, str):
2016-02-18 12:54:29 +00:00
print(r)
else:
2024-04-27 16:03:22 +01:00
print(f"response is unknown type: {type(r)}")
2017-08-17 00:33:02 +01:00
def submit(api_key, url, data, return_formatted=True):
"""
Sends an API POST request and acts as a generic formatter for the JSON response.
'data' will become the JSON payload read by Galaxy.
"""
try:
2017-08-17 00:33:02 +01:00
r = post(api_key, url, data)
2016-02-18 12:54:29 +00:00
except HTTPError as e:
2010-10-27 12:36:56 -04:00
if return_formatted:
2016-02-18 12:54:29 +00:00
print(e)
2017-08-17 00:33:02 +01:00
print(e.read(1024))
sys.exit(1)
2010-10-27 12:36:56 -04:00
else:
2017-08-17 00:33:02 +01:00
return "Error. " + str(e.read(1024))
2010-10-26 10:00:23 -04:00
if not return_formatted:
return r
2016-02-18 12:54:29 +00:00
print("Response")
print("--------")
2023-09-20 01:43:40 +01:00
if isinstance(r, list):
# Currently the only implemented responses are lists of dicts, because
# submission creates some number of collection elements.
for i in r:
2023-09-20 01:43:40 +01:00
if isinstance(i, dict):
if "url" in i:
2017-08-17 00:33:02 +01:00
print(i.pop("url"))
else:
2016-02-18 12:54:29 +00:00
print("----")
if "name" in i:
2024-04-27 16:03:22 +01:00
print(f" name: {i.pop('name')}")
for k, v in i.items():
2020-10-06 18:49:19 +01:00
print(f" {k}: {v}")
else:
2016-02-18 12:54:29 +00:00
print(i)
else:
2016-02-18 12:54:29 +00:00
print(r)
2010-10-26 10:00:23 -04:00
2017-08-17 00:33:02 +01:00
def update(api_key, url, data, return_formatted=True):
"""
Sends an API PUT request and acts as a generic formatter for the JSON response.
'data' will become the JSON payload read by Galaxy.
"""
2010-10-26 10:00:23 -04:00
try:
2017-08-17 00:33:02 +01:00
r = put(api_key, url, data)
2016-02-18 12:54:29 +00:00
except HTTPError as e:
2010-11-07 22:18:22 -05:00
if return_formatted:
2016-02-18 12:54:29 +00:00
print(e)
2017-08-17 00:33:02 +01:00
print(e.read(1024))
sys.exit(1)
2010-11-07 22:18:22 -05:00
else:
2017-08-17 00:33:02 +01:00
return "Error. " + str(e.read(1024))
2010-10-26 10:00:23 -04:00
if not return_formatted:
return r
2016-02-18 12:54:29 +00:00
print("Response")
print("--------")
print(r)
2017-08-17 00:33:02 +01:00
def delete(api_key, url, data, return_formatted=True):
"""
Sends an API DELETE request and acts as a generic formatter for the JSON response.
'data' will become the JSON payload read by Galaxy.
"""
2010-11-07 22:18:22 -05:00
try:
2017-08-17 00:33:02 +01:00
r = __del(api_key, url, data)
2016-02-18 12:54:29 +00:00
except HTTPError as e:
2010-11-07 22:18:22 -05:00
if return_formatted:
2016-02-18 12:54:29 +00:00
print(e)
2017-08-17 00:33:02 +01:00
print(e.read(1024))
sys.exit(1)
2010-11-07 22:18:22 -05:00
else:
2017-08-17 00:33:02 +01:00
return "Error. " + str(e.read(1024))
2010-11-07 22:18:22 -05:00
if not return_formatted:
return r
2016-02-18 12:54:29 +00:00
print("Response")
print("--------")
print(r)