Skip to content

Instantly share code, notes, and snippets.

@jweisman
Last active May 25, 2020 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jweisman/029b628120db219534c931b4f0b33126 to your computer and use it in GitHub Desktop.
Save jweisman/029b628120db219534c931b4f0b33126 to your computer and use it in GitHub Desktop.
Alma Invoice Attachments API
import os, sys, requests, base64, re
import xml.etree.ElementTree as ET
NS = {'exl': 'http://com/exlibris/repository/acq/invoice/xmlbeans'}
URL = 'https://api-na.hosted.exlibrisgroup.com'
def process_invoice( invoice ):
id = invoice.find('exl:unique_identifier', NS).text
number_of_attachments = invoice.find('exl:number_of_attachments', NS)
if (number_of_attachments is None or int(number_of_attachments.text) > 0):
get_attachments(id)
def get_attachments(invoice_id):
attachments = get(f"/almaws/v1/acq/invoices/{invoice_id}/attachments")
os.makedirs(invoice_id, exist_ok = True)
for attachment in attachments.findall('attachment'):
print(attachment.attrib['link'])
file_name, content = get_attachment(attachment.attrib['link'])
if not re.match(r"^ERP\..*\.xml$", file_name): # exclude export file
file = open(os.path.join(invoice_id, file_name) , 'wb')
file.write(base64.b64decode(content))
file.close()
def get_attachment(link):
attachment = get(link + "?expand=content")
return attachment.find('file_name').text, attachment.find('content').text
def get(url):
headers = {
'authorization': f"apikey {os.environ['ALMA_APIKEY']}",
'accept': 'application/xml'
}
if not url.startswith('https://'):
url = URL + url
response = requests.get(url, headers=headers)
response.raise_for_status()
return ET.fromstring(response.content)
def main():
directory = os.fsencode(sys.argv[1])
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".xml"):
xml = ET.parse(os.path.join(directory, file)).getroot()
for invoice in xml.findall('./exl:invoice_list/exl:invoice', NS):
process_invoice(invoice)
if len(sys.argv) <= 1:
print("Missing directory name")
exit()
main()
@jweisman
Copy link
Author

Usage:

$ python3 invoices.py {{directory}}

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