I am creating a Python script that retrieves images from CiviCRM. I don't just want the image name (which I retrieve with the uri field already) but the entire image url. How is that possible? I have tried the this (How to retrieve contact image URL in CiviCRM with the API) and that didn't give me the result I was looking for. please see code below:
import requests
import json
import os
import time
from util import *
server_time = datetime.datetime.now()
directory = os.environ.get('LOCAL_DIRECTORY')
def main():
def image_response(mime):
url = 'https://members.MY_CIVI_CRM_SITE.com/civicrm/ajax/api4/File/get'
params = {
'select': [
'id',
'mime_type',
'uri',
], 'where': [['mime_type', '=', f'image/{mime}']],
'limit': 100
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Civi-Auth': 'Bearer MYBEARERTOKEN'
}
all_contacts = []
# Retrieve data in batches of 100 using pagination
offset = 0
total_contacts = 0
while True:
try:
params['offset'] = offset
data = {'params': json.dumps(params)}
response = requests.post(url, headers=headers, data=data)
content = response.text
contacts = json.loads(content)['values']
all_contacts.extend(contacts)
# Update progress and break the loop if the retrieved contacts are less than the limit (i.e., the last batch)
num_retrieved = len(contacts)
total_contacts += num_retrieved
print(
f"Retrieved {num_retrieved} images. Total images: {total_contacts}")
if num_retrieved < params['limit']:
break
offset += params['limit']
except requests.exceptions.HTTPError as err:
exception_message = f'HTTP error occurred: {err}'
log_function(exception_message)
time.sleep(30)
# Continue with the next iteration of the loop
except requests.exceptions.RequestException as err:
exception_message = f'An error occurred during the request: {err}'
log_function(exception_message)
time.sleep(30)
# Continue with the next iteration of the loop
except Exception as err:
exception_message = f'An exception error occurred during the request: {err}'
log_function(exception_message)
time.sleep(30)
# Continue with the next iteration of the loop
return all_contacts
jpeg_images = image_response('jpeg')
png_images = image_response('png')
all_images = jpeg_images + png_images
# Save contacts to a JSON file
with open(f'{directory}/image_list.json', 'w') as file:
json.dump(all_images, file, indent=4)
message = "All images retrieved and saved to image_list.json"
print(message)
script_finish_time = datetime.datetime.now() - server_time
script_finish_time_split = str(script_finish_time).split('.')
script_complete_message = f'Script completed in {script_finish_time_split[0]}'
print(script_complete_message)
print("Phone numbers saved to image_list.json.")
if __name__ == "__main__":
main()```