REST API Examples
This page walks through the tasks most tools need: listing File Fields and their files, downloading every file of a
field, and adding small and large files. Each task lists the calls it takes and the part of fieldify_api_example.py
that makes them. The script uses Python's standard library only, so there is nothing to install, and it runs on
Windows, macOS and Linux. Copy it and adapt it for your own automation.
Set up the example script
Check what you need
- Python 3.9 or later.
- An allowed account and its OAuth 2.0 integration, set up as described in Set Up the REST API. The
integration needs
read:file-field:custom,write:file-field:custom,read:forge-app:jiraandoffline_access, and for theimportcommand alsoread:jira-workandwrite:jira-work. - The base URL as the Fieldify REST API page shows it, starting with
https://api.atlassian.com/svc/jira/. The script reads the cloud ID from it to call Jira's REST API.
Set the environment variables
The script reads its settings from environment variables.
| Variable | Value |
|---|---|
FIELDIFY_BASE_URL | Required. Your site's base URL, copied from the Fieldify REST API page. |
ATLASSIAN_CLIENT_ID | Required. Your integration's client ID, from the Developer Console. |
ATLASSIAN_CLIENT_SECRET | Required. Your integration's secret. |
ATLASSIAN_REDIRECT_URI | Required. The integration's callback URL, exactly as entered in the Developer Console. |
FIELDIFY_TOKEN_FILE | Optional. Where the script keeps its tokens. Default: fieldify-token.json in the folder you run it from. |
On macOS or Linux:
export FIELDIFY_BASE_URL="https://api.atlassian.com/svc/jira/<cloud-id>/apps/5f2edfae-1945-473f-874e-99fba4a4cba2_9dd13fa4-cc83-4cdd-8e68-459a0fbe97f7"
export ATLASSIAN_CLIENT_ID="<client ID>"
export ATLASSIAN_CLIENT_SECRET="<client secret>"
export ATLASSIAN_REDIRECT_URI="<callback URL>"
In Windows PowerShell, set each one as $env:FIELDIFY_BASE_URL = "<base URL>", and run the script with py instead of
python3.
Get the first refresh token
Open the authorization URL
Open the URL from the Marketplace App: Fieldify row of the Developer Console's generator, with
offline_accessadded to itsscopeparameter, and forimportalsoread:jira-workandwrite:jira-work.Accept as the allowed account
Pick your site and choose Accept.
Copy the code
The browser lands on your callback URL. Copy the value of the
codeparameter from its address.Exchange the code
Run the
exchangecommand with it. The script saves the tokens to the token file and prints the file's name and the scopes granted.
python3 fieldify_api_example.py exchange <code>
This is the part of the script that runs:
def exchange_code(settings, code):
"""Trade the authorization code from the consent for tokens, and save them.
Open the authorization URL that the Developer Console gives for Fieldify
(with offline_access among its scopes), grant consent as the account the
Jira administrator allowed, and copy the `code` parameter from the address
the browser lands on (ATLASSIAN_REDIRECT_URI).
"""
grant = token_request(
{
"grant_type": "authorization_code",
"client_id": settings["client_id"],
"client_secret": settings["client_secret"],
"code": code,
"redirect_uri": settings["redirect_uri"],
}
)
save_tokens(settings["token_file"], tokens_from(grant))
print(f"Saved the tokens to {settings['token_file']}.")
print(f"Scopes granted: {grant.get('scope', 'not listed')}")
if "refresh_token" not in grant:
print("No refresh token: add offline_access to the scopes, or the tokens stop working in an hour.")
You run exchange once. After that, every command refreshes the access token itself when it has expired.
List File Fields and their files
List File Fields gives the field IDs the other calls take, and List files in a field gives a field's current files on one work item.
The fields command prints the ID and name of each File Field on the site:
def list_fields(settings):
"""Print the File Fields on the site: the id other commands take, and the name."""
_, answer = call(settings, "GET", "/v1/fields")
for field in answer["fields"]:
print(f"{field['id']} {field['name']}")
if not answer["fields"]:
print("No File Fields on this site.")
python3 fieldify_api_example.py fields
customfield_10124 Supporting Documents
customfield_10123 Signed Contract
The files command prints one line per file in a field on a work item: its name, size, when it was added and how many
versions it has.
def list_files(settings, issue, field):
"""Return the field's current files on the work item (key such as SUP-12, or id)."""
query = urllib.parse.urlencode({"issue": issue, "field": field})
_, answer = call(settings, "GET", "/v1/files?" + query)
return answer["files"]
def show_files(settings, issue, field):
"""Print one line per file: name, size, when it was added, number of versions."""
files = list_files(settings, issue, field)
for file in files:
name = file.get("filename") or "(no name)"
added = file.get("uploadedAt") or "unknown"
print(f"{name} {file.get('size')} bytes added {added} versions {file.get('versions')}")
if not files:
print("No files in this field.")
python3 fieldify_api_example.py files CNT-42 customfield_10124
delivery-note.pdf 20001 bytes added 2026-11-23T19:43:17.896Z versions 1
packing-list.pdf 20001 bytes added 2026-11-23T19:45:07.550Z versions 1
inspection-report.pdf 300001 bytes added 2026-11-23T19:45:18.532Z versions 1
invoice.pdf 20001 bytes added 2026-11-23T22:01:41.709Z versions 1
certificate.pdf 300001 bytes added 2026-11-23T22:01:51.445Z versions 1
Download every file of a field
List the files
Call
GET /v1/fileswith the work item and the field.Request links
Send the
fileIdvalues toPOST /v1/files/links, up to 50 per call. Send thenotProcessedIDs, and themint-failedIDs whoseretryableistrue, again in a later call.Download each file
Fetch each
urlwith a plainGET, without the access token, before itsexpiresAt. Request a new link for one that expired. Name the file afterfilename, without any folder part it may contain.
The download command does this. It writes every file of a field into a folder, which it creates if it is missing, and
never overwrites a file already in the folder.
def download_files(settings, issue, field, folder):
"""Download every file of the field into `folder`.
POST /v1/files/links gives a one-hour link per file. Anyone holding a link
can download the file, so the script never prints or logs it. The link
points to another host: it is fetched without the access token. A file
already in the folder is never overwritten.
"""
file_ids = [file["fileId"] for file in list_files(settings, issue, field)]
if not file_ids:
print("No files in this field.")
return
os.makedirs(folder, exist_ok=True)
number = 0
failed = 0
while file_ids:
batch, file_ids = file_ids[:MAX_LINKS_PER_CALL], file_ids[MAX_LINKS_PER_CALL:]
_, answer = call(settings, "POST", "/v1/files/links", {"issue": issue, "field": field, "fileIds": batch})
for link in answer.get("links", []):
number += 1
if not save_link(link, folder, number):
failed += 1
for error in answer.get("errors", []):
failed += 1
print(f"Not downloaded: {error.get('code')}: {error.get('message')}")
# Ids the call had no time for come back in notProcessed: ask for them again.
not_processed = answer.get("notProcessed", [])
if not_processed and len(not_processed) == len(batch):
raise FieldifyError("The links call made no progress. Try again later.")
file_ids = not_processed + file_ids
if failed:
raise FieldifyError(
f"{failed} file(s) not downloaded. Run the command again, into an empty folder if files were already there."
)
python3 fieldify_api_example.py download CNT-42 customfield_10124 downloads
delivery-note.pdf: 20001 bytes
packing-list.pdf: 20001 bytes
inspection-report.pdf: 300001 bytes
invoice.pdf: 20001 bytes
certificate.pdf: 300001 bytes
Run into the same folder again, the script leaves the files there, reports each one and exits with code 1:
delivery-note.pdf: a file with this name is already in the folder; not overwritten
packing-list.pdf: a file with this name is already in the folder; not overwritten
inspection-report.pdf: a file with this name is already in the folder; not overwritten
invoice.pdf: a file with this name is already in the folder; not overwritten
certificate.pdf: a file with this name is already in the folder; not overwritten
Error: 5 file(s) not downloaded. Run the command again, into an empty folder if files were already there.
Add a small file
Encode the file
Read a file of up to 3,500,000 bytes and encode it in standard base64.
Upload it
Send it to
POST /v1/files/uploadwith the work item, the field and the file name. Readmodein the answer.Retry when asked
On
409busyor503, wait the seconds inRetry-After, or a few seconds when there is none, and send the same request again. If the answer was lost, sending it again is safe too.
The upload command does this. In a field that takes one file, the new file replaces the current one; in other fields
it is added next to the others.
def upload_file(settings, issue, field, path):
"""Add a file of up to 3,500,000 bytes, sent in the request as base64.
In a one-file field it replaces the current file; in other fields it is
added next to the others. Sending the same name and bytes again changes
nothing (mode "unchanged"), so a retry is safe.
"""
size = os.path.getsize(path)
if size > MAX_UPLOAD_BYTES:
raise FieldifyError(
f"The file has {size:,} bytes; upload takes at most {MAX_UPLOAD_BYTES:,}. Use the import command."
)
with open(path, "rb") as source:
content = source.read()
body = {
"issue": issue,
"field": field,
"filename": os.path.basename(path),
"contentBase64": base64.b64encode(content).decode("ascii"),
}
mime_type = mimetypes.guess_type(path)[0]
if mime_type:
body["mimeType"] = mime_type
_, answer = call(settings, "POST", "/v1/files/upload", body)
print(describe_write(answer))
python3 fieldify_api_example.py upload CNT-42 customfield_10123 contract-final.pdf
replaced: contract-final.pdf (15009 bytes), replacing 1 file(s)
A refusal prints the status, the API's error code and its message, and the script exits with code 1. Here the Supporting Documents field already holds its five files:
python3 fieldify_api_example.py upload CNT-42 customfield_10124 contract-final.pdf
Error: 409 field-full: This field already holds 5 files, the most its settings allow. Remove a file first.