Skip to content

Table Operation: Retrieve Attachments

Overview

This API retrieves information about files attached to attachment column, and image files pasted into content, description column, and comments.

Limitations

  1. This API retrieves file information. Please perform the conversion (Base64 Decode) to retrieve the actual file. Please refer to the following FAQ for the conversion process.

FAQ: Sample Code: Download Attachments

Preparations

Please Create an API Key before performing API operations.

Setting column Value
HTTP Method POST
Content-Type application/json
Character Code UTF-8
URL http://{server name}/api/binaries/{Guid}/get(*1)
Body See the json data below for reference

(*1) Please edit the {server name} and {Guid} parts suit your environment as appropriate.
For Pleasanter.net, the format is as follows:
https://pleasanter.net/fs/api/binaries/{Guid}/get

(*2)
If you want to retrieve record information including the Guid of an attachment, please follow the link below.
API Function: Retrieve Single Record

Request

JSON
{
     "ApiVersion": 1.1,
     "ApiKey": "234S567dStfghjkA..."
}

Response

The json data in the following format will be returned.

Acquired column Description
Id The ID of the record in the Binaries table that was acquired is stored.
StatusCode The status code upon completion is stored. The value is 200 when the operation is successful.
Message The message upon completion is stored.
ReferenceId The ID of the record to which the file is linked is stored.
BinaryType Attachments is stored for attachments, and Images is stored for images.
Base64 The contents of the file encoded in Base64 are stored. To obtain the actual file, decode this value with Base64.
Guid The GUID of the file is stored.
FileName The file name is stored.
Extension The extension is stored.
Size The file size in bytes is stored.
ContentType The MimeType of the file is stored.
Creator The user ID of the file creator is stored.
Updater The user ID of the file updater is stored.
CreatedTime The file creation datetime is stored.
UpdatedTime The file update datetime is stored.
JSON
{
    "Id": 123,
    "StatusCode": 200,
    "Message": "Test file is retrieved.",
    "Response": {
        "ReferenceId": 30,
        "BinaryType": "Attachments",
        "Base64": "dGVzdA==...",
        "Guid": "5E23245...",
        "FileName": "Test file",
        "Extension": ".txt",
        "Size": 54,
        "ContentType": "text/plain",
        "Creator": 1,
        "Updator": 1,
        "CreatedTime": "2023/08/16 12:00:00",
        "UpdatedTime": "2023/08/17 12:00:00"
    }
}

Code Samples

Modify 【 ... 】 in the code as necessary.
1. Get all attachments saved in a table at once

Gets the files attached to the records of a table at once. The records to get are narrowed down with View, and when attachments exist, a folder is created for each ID and the files are stored in it.

Python(api_binaries_p1.py)
# Base64 encoding/decoding library
import base64

# Library for regular expressions
import re

# Library for file path operations
from pathlib import Path

# Library for HTTP requests
import requests

# Settings
BASE_URI = "【URL】"
API_KEY = "【API key】"
SITE_ID = 【Site ID】
API_VERSION = 1.1

# Attachment column to get
ATTACHMENT_ITEM = "AttachmentsA"
# Destination directory
OUT_DIR = Path(r"C:\work\download")

# Replace characters that cannot be used in file names and convert to a safe name
safe = lambda s: re.sub(r'[\\/:*?"<>|\x00-\x1F]', "_", str(s or "")).strip()

# Search condition (narrow down to records whose Status is 100)
VIEW = {
    "ColumnFilterHash": {
        "Status": '["100"]',
    }
}

post = lambda s, url, payload: (lambda r: (r.raise_for_status(), r.json())[1])(
    s.post(
        url, json=payload, headers={"Content-Type": "application/json; charset=utf-8"}
    )
)

# Main process
OUT_DIR.mkdir(parents=True, exist_ok=True)

# Variables for totaling the results
record_count = 0  # Number of records retrieved
records_with_attachments = 0  # Number of records with attachments
seen_files = 0  # Total number of attachments
downloaded_files = 0  # Number of files actually downloaded

with requests.Session() as s:
    # Get the records
    items = (
        post(
            s,
            f"{BASE_URI}/api/items/{SITE_ID}/get",
            {"ApiVersion": API_VERSION, "ApiKey": API_KEY, "View": VIEW},
        )
        .get("Response", {})
        .get("Data", [])
    )

    record_count = len(items)

    for rec in items:
        rec_id = rec.get("ResultId") or rec.get("IssueId")
        atts = (rec.get("AttachmentsHash") or {}).get(ATTACHMENT_ITEM) or []
        if not rec_id or not atts:
            continue  # No attachments -> do not create a folder

        records_with_attachments += 1
        rec_dir = OUT_DIR / str(rec_id)
        rec_dir.mkdir(parents=True, exist_ok=True)

        # Loop to get the attachments
        for a in atts:
            guid, name = a.get("Guid"), a.get("Name")
            if not guid or not name:
                continue

            seen_files += 1
            b64 = (
                post(
                    s,
                    f"{BASE_URI}/api/binaries/{guid}/get",
                    {"ApiVersion": API_VERSION, "ApiKey": API_KEY},
                )
                .get("Response", {})
                .get("Base64")
            )

            if not b64:
                continue
            # Save the file
            (rec_dir / safe(name)).write_bytes(base64.b64decode(b64))
            downloaded_files += 1

# Output the processing results
print("=== Download Result ===")
print(f"SiteId                : {SITE_ID}")
print(f"Attachment Item       : {ATTACHMENT_ITEM}")
print(f"Records (matched)     : {record_count}")
print(f"Records with files    : {records_with_attachments}")
print(f"Attachments found     : {seen_files}")
print(f"Attachments downloaded: {downloaded_files}")
print(f"Output directory      : {OUT_DIR}")
Run
>python api_binaries_p1.py
Execution Result
=== Download Result ===
SiteId                : 6412
Attachment Item       : AttachmentsA
Records (matched)     : 1
Records with files    : 0
Attachments found     : 0
Attachments downloaded: 0
Output directory      : C:\work\download

Confirmation Column in Case of Error

・Precautions when using the API and things to check if an error occurs
・FAQ: What to check if modified configuration files or API requests (JSON format) are not recognized correctly

Specification Changes

*API specifications have been partially changed since November 2018.**
- The URL format has been changed from '/pleasanter/api_items/xxxx' to '/pleasanter/api/items/xxxx'.
- The Content-Type specification has been changed from 'application/x-www-form-urlencoded' to 'application/json'.