Skip to content

Instantly share code, notes, and snippets.

@danizen
Created November 18, 2020 20:42
Show Gist options
  • Save danizen/3e460db99637ed37f9d7dcca64bfbdec to your computer and use it in GitHub Desktop.
Save danizen/3e460db99637ed37f9d7dcca64bfbdec to your computer and use it in GitHub Desktop.
Python3 script to access Alma APIs
#!/usr/bin/env python3
import sys
from argparse import ArgumentParser
from io import BytesIO
import requests
from lxml import etree
DFLT_ENDPOINT = 'https://api-na.hosted.exlibrisgroup.com'
def get_bibs(mms_ids, endpoint=DFLT_ENDPOINT, api_key=None, pretty=False):
session = requests.Session()
session.headers.update({
'Authorization': f'apikey {api_key}'
})
bib_url = f'{endpoint}/almaws/v1/bibs'
response = session.get(bib_url, params={'mms_id': ','.join(mms_ids)})
if pretty:
doc = etree.parse(BytesIO(response.content))
print(etree.tostring(
doc.getroot(), encoding="utf-8", pretty_print=True
).decode('utf-8'))
else:
print(response.content.decode('utf-8'))
def create_parser(program_name):
parser = ArgumentParser(
prog=program_name,
description="Utility to get bibs from ExLibris"
)
parser.add_argument('--endpoint', metavar='URL', default=DFLT_ENDPOINT,
help='Change the endpoint for bib utility')
parser.add_argument('--api-key', metavar='KEY', default=None, required=True,
help='The API key defines the institution to query')
parser.add_argument('--pretty', action='store_true', default=False,
help='Pretty print the XML')
parser.add_argument('mms_id', nargs='+')
return parser
def main_guts(args):
parser = create_parser(args[0])
opts = parser.parse_args(args[1:])
return get_bibs(
opts.mms_id,
endpoint=opts.endpoint,
api_key=opts.api_key,
pretty=opts.pretty
)
def main():
rc = main_guts(sys.argv)
if rc:
sys.exit(rc)
if __name__ == '__main__':
main()
@danizen
Copy link
Author

danizen commented Nov 18, 2020

To use this, you would need to install the Python package "requests" and "lxml" as follows:

pip install requests lxml

Once you have installed this, you can call the API for an MMS_ID, for example 991125260000541, as follows:

python getbibs.py --api-key l8xx111111111 991125260000541

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment