Using API to upload media files?

@Josh It works beautifully! Many thanks.
I did some experimenting and I found that ODK will download the new CSV file if you sync manually, even if you don’t redeploy the form. Here’s the final python script for anyone who wants to programmatically upload the CSV file for pulldata purposes:

    import requests
    import json

    KC_URL = 'https://<kc_url>/api/v1/'
    KF_URL = 'https://<kf_url>/api/v2/'

    TOKEN = '<token>'      
    XFORM = <xform_id>

    FILE_FOLDER = r"<file_folder>"
    FILENAME = '<file_name>'
    MIME = 'text/csv'


    headers = {'Authorization': f'Token {TOKEN}'}
    files = {'data_file': (FILENAME, open(fr'{FILE_FOLDER}\{FILENAME}', 'rb').read(), MIME)}
    data = {
        'data_value': FILENAME,
        'xform': XFORM,
        'data_type': 'media',
        'data_file_type': MIME,
    }

    # Download metadata.json
    response = requests.get(fr"{KC_URL}/metadata.json", headers=headers)
    dict_response = json.loads(response.text)

    # Delete appropriate entry in the metadata.json (delete old file)
    for each in dict_response:
        if each['xform'] == XFORM and each['data_value'] == FILENAME:
            del_id = each['id']
            response = requests.delete(fr"{KC_URL}/metadata/{del_id}", headers=headers)
            break

    # Upload the changed file
    response = requests.post(fr"{KC_URL}/metadata.json", data=data, files=files, headers=headers)
4 Likes