Skip to content

Instantly share code, notes, and snippets.

@raprasad
Last active June 27, 2018 16:14
Show Gist options
  • Save raprasad/044d455cb6a09b9a0f965e08dd564098 to your computer and use it in GitHub Desktop.
Save raprasad/044d455cb6a09b9a0f965e08dd564098 to your computer and use it in GitHub Desktop.
Dataverse: add a file to a Dataset using a persistentID

source: http://guides.dataverse.org/en/latest/api/native-api.html

import os
from datetime import datetime
import json
import requests  # http://docs.python-requests.org/en/master/

# --------------------------------------------------
# Update the 3 params below to run this code
# --------------------------------------------------
dataverse_server = 'https://dataverse.harvard.edu' # no trailing slash
api_key = os.environ.get('DV_API_KEY', 'default api key')
persistentId = 'doi:10.5072/FK2/6XACVA' # doi or hdl of the dataset

# --------------------------------------------------
# Prepare "file"
# --------------------------------------------------
file_content = 'content: %s' % datetime.now()
files = {'file': ('sample_file.txt', file_content)}

# --------------------------------------------------
# Using a "jsonData" parameter, add optional description + file tags
# --------------------------------------------------
params = dict(description='Blue skies!',
            categories=['Lily', 'Rosemary', 'Jack of Hearts'])

params_as_json_string = json.dumps(params)

payload = dict(jsonData=params_as_json_string)

# --------------------------------------------------
# Add file using the Dataset's persistentId (e.g. doi, hdl, etc)
# --------------------------------------------------
url_persistent_id = '%s/api/datasets/:persistentId/add?persistentId=%s&key=%s' % (dataverse_server, persistentId, api_key)

# -------------------
# Make the request
# -------------------
print '-' * 40
print 'making request: %s' % url_persistent_id
r = requests.post(url_persistent_id, data=payload, files=files)

# -------------------
# Print the response
# -------------------
print '-' * 40
print r.json()
print r.status_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment