How to replace csv media file or delete existing media file using kobo v2 API

Okay @Kal_Lam, please find below the developed Python script that does the following

  • Deletes a media file (input.csv)
  • Uploads a new media file (input.csv)
  • Redeploy form to display the newly uploaded media file.

The script:

import requests, json

URL = 'https://<url>/api/v2/'
TOKEN = '<token>'
XFORM = '<form_id>'

headers = {'Authorization': f'Token {TOKEN}'}

#### TO DELETE OLD MEDIA FILE
try:
    data_url = "%sassets/%s/files/" % (URL, XFORM)

    response = requests.get(data_url, headers=headers, params={'format': 'json'})
    json_uid = response.json()
    media_uid = json_uid['results'][0]['uid']
    asset_url = "%s/%s/" % (data_url, media_uid)
    res = requests.delete(asset_url, headers=headers)
    print(res)
    print("Old media file deleted successfully")
except:
    print("No media file uploaded")
    pass
#### TO UPLOAD NEW MEDIA FILE

try:
    KC_URL= "%sassets/%s/files.json" % (URL, XFORM)

    FILENAME = 'input.csv'
    MIME = 'text/csv'

    payload = {'filename': 'input.csv'}
    files = {'content': open('input.csv', 'rb')}
    data = {'description': 'Input and equipment media file', 'metadata': json.dumps(payload), 'file_type': 'form_media'}

    res = requests.post(url=KC_URL, headers=headers, data=data, files=files)
    print(res)
    print("New media file uploaded successfully")
except:
    print("No media file")

#### TO REDEPLOY FORM

asset_url = "%sassets/%s/" % (URL, XFORM)
headers = {
    'Accept': 'application/json',
    'Authorization': f'Token {TOKEN}'
}

response = requests.get(asset_url, headers=headers, params={'format': 'json'})
version_to_deploy = response.json()['version_id']
deployment_data = {
    'version_id': version_to_deploy,
    'active': True
}
response = requests.patch(asset_url + 'deployment/', headers=headers, data=deployment_data)
print(response)
print("Form redeployed successfully")
3 Likes