Skip to main content

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.

Download the script


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:jira and offline_access, and for the import command also read:jira-work and write: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.

VariableValue
FIELDIFY_BASE_URLRequired. Your site's base URL, copied from the Fieldify REST API page.
ATLASSIAN_CLIENT_IDRequired. Your integration's client ID, from the Developer Console.
ATLASSIAN_CLIENT_SECRETRequired. Your integration's secret.
ATLASSIAN_REDIRECT_URIRequired. The integration's callback URL, exactly as entered in the Developer Console.
FIELDIFY_TOKEN_FILEOptional. 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​

  1. Open the authorization URL

    Open the URL from the Marketplace App: Fieldify row of the Developer Console's generator, with offline_access added to its scope parameter, and for import also read:jira-work and write:jira-work.

  2. Accept as the allowed account

    Pick your site and choose Accept.

  3. Copy the code

    The browser lands on your callback URL. Copy the value of the code parameter from its address.

  4. Exchange the code

    Run the exchange command 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​

  1. List the files

    Call GET /v1/files with the work item and the field.

  2. Request links

    Send the fileId values to POST /v1/files/links, up to 50 per call. Send the notProcessed IDs, and the mint-failed IDs whose retryable is true, again in a later call.

  3. Download each file

    Fetch each url with a plain GET, without the access token, before its expiresAt. Request a new link for one that expired. Name the file after filename, 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​

  1. Encode the file

    Read a file of up to 3,500,000 bytes and encode it in standard base64.

  2. Upload it

    Send it to POST /v1/files/upload with the work item, the field and the file name. Read mode in the answer.

  3. Retry when asked

    On 409 busy or 503, wait the seconds in Retry-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.

Add a large file through an attachment​

A file larger than an upload takes, up to 100 MB and the field's own size limit, goes through a Jira attachment. The integration needs the Jira scopes read:jira-work and write:jira-work for this, and the allowed account needs permission to add attachments to the work item and to delete its own attachments. With an OAuth 2.0 token, Jira's REST API is called at https://api.atlassian.com/ex/jira/<cloud-id>/rest/api/3.

  1. Attach the file

    Send the file to Jira's POST /issue/<work item key>/attachments as a multipart form with one part named file, and the header X-Atlassian-Token: no-check. The id of the first item in Jira's answer is the attachment ID.

  2. Start the import

    Send the attachment ID to POST /v1/files/import. It answers 202 with statusPath and a Retry-After header.

  3. Wait for the copy

    Wait the seconds in Retry-After, then send GET to the base URL followed by statusPath. Repeat while the answer is 202. A 200 means the import has finished: with status succeeded, result holds the file and the mode; with status failed, error holds the code.

  4. Delete the attachment

    Delete the attachment with Jira's DELETE /attachment/<attachment ID>, also when the import failed. Jira answers 204.

The import command does this, and deletes the attachment even when the import fails or takes too long:

def import_file(settings, issue, field, path):
"""Add a file larger than the upload takes, up to the field's own size limit.

Three steps: attach the file to the work item with Jira's REST API, let
Fieldify copy the attachment into the field, delete the attachment. The
attachment is deleted even when the import fails or takes too long.
"""
attachment_id = add_attachment(settings, issue, path)
try:
body = {"issue": issue, "field": field, "attachmentId": attachment_id}
_, job = call(settings, "POST", "/v1/files/import", body)
job = wait_for_import(settings, job)
finally:
delete_attachment(settings, attachment_id)
if job["status"] == "failed":
error = job.get("error") or {}
raise FieldifyError(f"The import failed: {error.get('code')}: {error.get('message')}")
print(describe_write(job["result"]))

The wait asks for the import's status until it has finished, and gives up after 10 minutes:

def wait_for_import(settings, job):
"""Ask for the import's status at its statusPath until it has succeeded or failed.

Each 202 answer says how long to wait before asking again: the Retry-After
header, which the body repeats as retryAfterSeconds. Gives up after 10 minutes.
"""
status_path = job["statusPath"]
give_up_at = time.monotonic() + IMPORT_TIMEOUT_SECONDS
while job["status"] in ("queued", "running"):
if time.monotonic() > give_up_at:
raise FieldifyError(
"The import did not finish within 10 minutes. Run the command again: "
"if the first copy finished meanwhile, the second changes nothing."
)
print(f"Import {job['status']}...")
time.sleep(job.get("retryAfterSeconds", DEFAULT_WAIT_SECONDS))
_, job = call(settings, "GET", status_path)
return job
python3 fieldify_api_example.py import CNT-42 customfield_10123 contract-scan.pdf
Import queued...
Deleted the temporary attachment.
replaced: contract-scan.pdf (300009 bytes), replacing 1 file(s)

Adapt the script​

The work item and the field are arguments of each command, and so is the download folder, so a scheduled job passes its own. The limits and waits are constants at the top of the script:

TOKEN_URL = "https://auth.atlassian.com/oauth/token"
MAX_UPLOAD_BYTES = 3_500_000 # larger files go through `import`
MAX_LINKS_PER_CALL = 50 # file ids in one POST /v1/files/links
MAX_RETRIES = 3 # for `busy` and 503 answers
DEFAULT_WAIT_SECONDS = 5 # when an answer does not say how long to wait
IMPORT_TIMEOUT_SECONDS = 10 * 60 # how long `import` waits for the copy

MAX_RETRIES sets how often a call is tried again after busy or 503. Every request to Fieldify goes through call:

def call(settings: dict, method: str, path: str, body: dict = None) -> tuple[int, dict]:
"""Call one Fieldify endpoint; return (status, answer). JSON in and out.

`busy` (another write into the same field) and 503 (Fieldify unavailable
for a moment) are tried again up to 3 times, after the wait the Retry-After
header asks for, or 5 seconds. Any other error raises FieldifyError with
the API's error code and message.
"""
data = None if body is None else json.dumps(body).encode("utf-8")
for attempt in range(1 + MAX_RETRIES):
request = urllib.request.Request(settings["base_url"] + path, data=data, method=method)
request.add_header("Accept", "application/json")
if data is not None:
request.add_header("Content-Type", "application/json")
status, headers, raw = send(with_token(request, settings))
answer = parse_json(raw)
if status < 400:
return status, answer
error = answer.get("error")
code = error.get("code") if isinstance(error, dict) else None
if (code == "busy" or status == 503) and attempt < MAX_RETRIES:
wait = retry_after(headers)
print(f"{code or status}: trying again in {wait} s")
time.sleep(wait)
continue
raise FieldifyError(describe_error(status, answer))

Each task is a function of its own (list_files, download_files, upload_file, import_file), so you can keep the ones you need and call them from your own code with the settings that load_settings returns.


Keep the token file safe​

The token file holds a refresh token and the current access token. Store it like a password. On macOS and Linux the script creates it readable by your user only; on Windows, keep it in a folder only you can open. The script never prints a token, the client secret or a download link.

Refresh tokens rotate: each refresh returns a new one, and only that one works next time. The script saves it before it uses the new access token, and stops if it cannot:

def access_token(settings: dict) -> str:
"""Return a valid access token, refreshing it with the saved refresh token when it has expired.

The refresh answers with a new refresh token, and only that one will work
next time, so it is saved before the access token is used. If it cannot be
saved, the script stops.
"""
tokens = read_tokens(settings["token_file"])
if tokens.get("access_token") and tokens.get("expires_at", 0) > time.time():
return tokens["access_token"]
if not tokens.get("refresh_token"):
raise SystemExit("The token file holds no refresh token. Run `exchange` again, with offline_access.")
grant = token_request(
{
"grant_type": "refresh_token",
"client_id": settings["client_id"],
"client_secret": settings["client_secret"],
"refresh_token": tokens["refresh_token"],
}
)
new_tokens = tokens_from(grant, tokens["refresh_token"])
try:
save_tokens(settings["token_file"], new_tokens)
except OSError as error:
raise SystemExit(
f"Could not save the new refresh token to {settings['token_file']} ({error}). "
"Stopping here. If the next run cannot refresh, run `exchange` with a new code."
)
return new_tokens["access_token"]

If the refresh token has expired or the consent was revoked, the script says so. Run exchange again with a new code.