How to upload images as attachment via API with Python?

Self-explanatory title :slight_smile:
I have URLs for images that I would like to attach in the Grist records (not just the URL of it).
Seems I’m missing a trick here and couldn’t find anything searching this forum.

Using python3 with the grist_api library.

Thanks for your help!

There isn’t anything in the grist_api library, so you’ll need to use the API directly: REST API reference - Grist Help Center

In Python:

import requests

response = requests.post(
    f"https://docs.getgrist.com/api/docs/{doc_id}/attachments",
    files={"upload": open("my_pic.png", "rb")},
    headers={"Authorization": f"Bearer {api_key}"},
)
attachment_id = response.json()[0]
cell_value = ["L", attachment_id]

Then use add_records or update_records and pass cell_value as the value of a single cell in an Attachments type column.

2 Likes

This works. Thank you so much Alex! :pray:t3:

For my understanding: how can I manage attachments in a doc (eg see all, delete, etc…) if only the ref to the attachment is included in the cell?

See the other endpoints in REST API reference - Grist Help Center for listing/downloading attachments.

If an attachment is not referenced by any cell, it will be deleted automatically after some time. If you need to delete it immediately, there’s an undocumented endpoint: POST /api/docs/{doc_id}/attachments/removeUnused. Use it with caution.

3 Likes

Thanks a lot Alex. I will try that out if needed - with caution!

@alexmojaki Thank you for this help and it would be great to add it on API reference documentation (payload sample for instance):

#add records to table with attachment:
POST /api/docs/{docId}/tables/{tableId}/records
# sample payload:
{"records": [{ "fields": { "file": ["L", attachment_id] }}]

Or here: Module: GristData - Grist Help Center