How to upload files via RESTful API and link them to Attachments fields
While it’s possible to upload attachments to records via the Swimlane Python driver, it’s also possible to do it directly by using the API. This guide will give a brief overview of how to use the RESTful API to upload files to a record and link them to an attachment field.
- First, import the packages and connect to the RESTful API:
from swimlane import Swimlane
import json
swimlane = Swimlane('HOST', 'USER', 'PASSWORD', verify_ssl=False)
- Post the byte stream to the RESTful API:
file_name = 'api_pod_logs.txt'
file_path = r'C:\user\Swimlane\api_pod_logs.txt'
resp = swimlane.request('post','/attachment', files={'file':(file_name, open(file_path, 'rb'))}, verify=False)
resp.raise_for_status()
rdata = resp.json()[0]
- Finally, link the byte stream’s identifier to the Swimlane record:
resp = swimlane.request('get', '/app/{}/record/{}'.format('aVGJPJ3E43TkwTQY5','aL_KhxQqZkD1IwYNE'))
resp.raise_for_status()
rec_DB12_1 = resp.json()
rec_DB12_1['values']['afihc'].append({'$type':'Core.Models.Record.Attachment, Core', 'fileId':rdata['fileId'], 'filename':file_name, 'uploadDate':rdata['uploadDate']})
resp = swimlane.request('put', '/app/{}/record/{}'.format('aVGJPJ3E43TkwTQY5','aL_KhxQqZkD1IwYNE'), json=rec_DB12_1)
Some additional notes:
- We’re only using the Swimlane driver to connect to the API. The rest is all done with API calls.
- When the file is uploaded, it’s stored in a segmented fashion by using MongoDB’s GridFS feature.
- The files are stored in two separate collections (fs_files, and fs_chunks)
The full code:
from swimlane import Swimlane
import json
# connect to RESTful API
swimlane = Swimlane('HOST', 'USER', 'PASSWORD', verify_ssl=False)
# post the byte stream to RESTful API
file_name = 'api_pod_logs.txt'
file_path = r'<filename_example>.txt'
resp = swimlane.request('post','/attachment', files={'file':(file_name, open(file_path, 'rb'))}, verify=False)
resp.raise_for_status()
rdata = resp.json()[0]
# link the byte stream's identifier to the Swimlane record
resp = swimlane.request('get', '/app/{}/record/{}'.format('aVGJPJ3E43TkwTQY5','aL_KhxQqZkD1IwYNE'))
resp.raise_for_status()
rec_DB12_1 = resp.json()
rec_DB12_1['values']['afihc'].append({'$type':'Core.Models.Record.Attachment, Core', 'fileId':rdata['fileId'], 'filename':file_name, 'uploadDate':rdata['uploadDate']})
resp = swimlane.request('put', '/app/{}/record/{}'.format('aVGJPJ3E43TkwTQY5','aL_KhxQqZkD1IwYNE'), json=rec_DB12_1)