0

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()```

1 Answer 1

0

You have to use Attachments, which is only available in API 3. See previous question here.

7
  • Thank you for your prompt response, but I have tried this url and it does not work https://members.wfto.com/civicrm/custom/orgchart.jpg . Could this be a permissions issue? Jul 3, 2023 at 8:50
  • Have you double checked that URL is correct with one of the images within CiviCRM?
    – Lars SG
    Jul 3, 2023 at 14:02
  • Alternatively, there is an extension that exports all of these: civicrm.org/extensions/exportphotos
    – Lars SG
    Jul 3, 2023 at 14:02
  • Sadly, that solution isn't what my client wants. They expect a json file output with image url's. That json file will be used to import data into a wordpress site. in the beginning of the project I was able to use this url: https://members.wfto.com/civicrm/file/imagefile/10-10.png . The client has made changes to the CRM and now that url doesn't work anymore. The client has said they have reverted changes but I'm still not able to use this url. That's why I am searching for an alternative. Jul 4, 2023 at 9:24
  • Did you see this question? I think it answers what you're looking for. civicrm.stackexchange.com/questions/28754/…
    – Lars SG
    Jul 4, 2023 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.