API

PyCap is structured into two layers: a high level that exposes redcap.Project and a low-level, redcap.request. Users (like yourself) should generally only worry about working the redcap.Project class.

JSON Handling

For any request with a format='json' argument, the API will respond with a JSON-formatted string representation of the response. This is automatically decoded by PyCap into a list of python dictionaries. This is the default format for all requests.

High-Level

The redcap.Project class is the high-level object of the module. Generally you’ll only need this class.

class redcap.project.Project(url, token, name='', verify_ssl=True, lazy=False)[source]

Main class for interacting with REDCap projects

__init__(url, token, name='', verify_ssl=True, lazy=False)[source]
Parameters:
url : str

API URL to your REDCap server

token : str

API token to your project

name : str, optional

name for project

verify_ssl : boolean, str

Verify SSL, default True. Can pass path to CA_BUNDLE.

backfill_fields(fields, forms)[source]

Properly backfill fields to explicitly request specific keys. The issue is that >6.X servers only return requested fields so to improve backwards compatiblity for PyCap clients, add specific fields when required.

Parameters:
fields: list

requested fields

forms: list

requested forms

Returns:
new fields, forms
delete_file(record, field, return_format='json', event=None)[source]

Delete a file from REDCap

Parameters:
record : str

record ID

field : str

field name

return_format : ('json'), 'csv', 'xml'

return format for error message

event : str

If longitudinal project, event to delete file from

Returns:
response : dict, str

response from REDCap after deleting file

Notes

There is no undo button to this.

delete_records(records)[source]

Delete records from the Project.

Parameters:
records : list

List of record IDs that you want to delete from the project

Returns:
response : int

Number of records deleted

export_fem(arms=None, format='json', df_kwargs=None)[source]

Export the project’s form to event mapping

Parameters:
arms : list

Limit exported form event mappings to these arm numbers

format : ('json'), 'csv', 'xml'

Return the form event mappings in native objects, csv or xml, 'df'' will return a pandas.DataFrame

df_kwargs : dict

Passed to pandas.read_csv to control construction of returned DataFrame

Returns:
fem : list, str, pandas.DataFrame

form-event mapping for the project

export_file(record, field, event=None, return_format='json')[source]

Export the contents of a file stored for a particular record

Parameters:
record : str

record ID

field : str

field name containing the file to be exported.

event: str

for longitudinal projects, specify the unique event here

return_format: (‘json’), ‘csv’, ‘xml’

format of error message

Returns:
content : bytes

content of the file

content_map : dict

content-type dictionary

Notes

Unlike other export methods, this works on a single record.

export_metadata(fields=None, forms=None, format='json', df_kwargs=None)[source]

Export the project’s metadata

Parameters:
fields : list

Limit exported metadata to these fields

forms : list

Limit exported metadata to these forms

format : ('json'), 'csv', 'xml', 'df'

Return the metadata in native objects, csv or xml. 'df' will return a pandas.DataFrame.

df_kwargs : dict

Passed to pandas.read_csv to control construction of returned DataFrame. by default {'index_col': 'field_name'}

Returns:
metadata : list, str, pandas.DataFrame

metadata sttructure for the project.

export_project_info(format='json')[source]

Export Project Information

Parameters:
format: (json, xml, csv), json by default

Format of returned data

export_records(records=None, fields=None, forms=None, events=None, raw_or_label='raw', event_name='label', format='json', export_survey_fields=False, export_data_access_groups=False, df_kwargs=None, export_checkbox_labels=False, filter_logic=None, date_begin=None, date_end=None)[source]

Export data from the REDCap project.

Parameters:
records : list

array of record names specifying specific records to export. by default, all records are exported

fields : list

array of field names specifying specific fields to pull by default, all fields are exported

forms : list

array of form names to export. If in the web UI, the form name has a space in it, replace the space with an underscore by default, all forms are exported

events : list

an array of unique event names from which to export records

note:this only applies to longitudinal projects
raw_or_label : ('raw'), 'label', 'both'

export the raw coded values or labels for the options of multiple choice fields, or both

event_name : ('label'), 'unique'

export the unique event name or the event label

format : ('json'), 'csv', 'xml', 'df'

Format of returned data. 'json' returns json-decoded objects while 'csv' and 'xml' return other formats. 'df' will attempt to return a pandas.DataFrame.

export_survey_fields : (False), True

specifies whether or not to export the survey identifier field (e.g., “redcap_survey_identifier”) or survey timestamp fields (e.g., form_name+”_timestamp”) when surveys are utilized in the project.

export_data_access_groups : (False), True

specifies whether or not to export the "redcap_data_access_group" field when data access groups are utilized in the project.

note:This flag is only viable if the user whose token is being used to make the API request is not in a data access group. If the user is in a group, then this flag will revert to its default value.
df_kwargs : dict

Passed to pandas.read_csv to control construction of returned DataFrame. by default, {'index_col': self.def_field}

export_checkbox_labels : (False), True

specify whether to export checkbox values as their label on export.

filter_logic : string

specify the filterLogic to be sent to the API.

date_begin : datetime

for the dateRangeStart filtering of the API

date_end : datetime

for the dateRangeEnd filtering snet to the API

Returns:
data : list, str, pandas.DataFrame

exported data

export_reports(format='json', report_id=None, raw_or_label='raw', raw_or_label_headers='raw', export_checkbox_labels='false', decimal_character=None, df_kwargs=None)[source]

Export a report of the Project

Parameters:
report_id : the report ID number provided next to the report name

on the report list page

format : ('json'), 'csv', 'xml', 'df'

Format of returned data. 'json' returns json-decoded objects while 'csv' and 'xml' return other formats. 'df' will attempt to return a pandas.DataFrame.

raw_or_label : raw [default], label - export the raw coded values or

labels for the options of multiple choice fields

raw_or_label_headers : raw [default], label - (for ‘csv’ format ‘flat’

type only) for the CSV headers, export the variable/field names (raw) or the field labels (label)

export_checkbox_labels : true, false [default] - specifies the format of

checkbox field values specifically when exporting the data as labels (i.e., when rawOrLabel=label). When exporting labels, by default (without providing the exportCheckboxLabel flag or if exportCheckboxLabel=false), all checkboxes will either have a value ‘Checked’ if they are checked or ‘Unchecked’ if not checked. But if exportCheckboxLabel is set to true, it will instead export the checkbox value as the checkbox option’s label (e.g., ‘Choice 1’) if checked or it will be blank/empty (no value) if not checked. If rawOrLabel=false, then the exportCheckboxLabel flag is ignored.

decimal_character : If specified, force all numbers into same decimal

format. You may choose to force all data values containing a decimal to have the same decimal character, which will be applied to all calc fields and number-validated text fields. Options include comma ‘,’ or dot/full stop ‘.’, but if left blank/null, then it will export numbers using the fields’ native decimal format. Simply provide the value of either ‘,’ or ‘.’ for this parameter.

Returns:
Per Redcap API:
Data from the project in the format and type specified
Ordered by the record (primary key of project) and then by event id
export_survey_participant_list(instrument, event=None, format='json')[source]

Export the Survey Participant List

Parameters:
instrument: str

Name of instrument as seen in second column of Data Dictionary.

event: str

Unique event name, only used in longitudinal projects

format: (json, xml, csv), json by default

Format of returned data

Notes

The passed instrument must be set up as a survey instrument.

export_users(format='json')[source]

Export the users of the Project

Parameters:
format : ('json'), 'csv', 'xml'

response return format

Returns:
users: list, str

list of users dicts when 'format'='json', otherwise a string

Notes

Each user will have the following keys:

  • 'firstname' : User’s first name
  • 'lastname' : User’s last name
  • 'email' : Email address
  • 'username' : User’s username
  • 'expiration' : Project access expiration date
  • 'data_access_group' : data access group ID
  • 'data_export' : (0=no access, 2=De-Identified, 1=Full Data Set)
  • 'forms' : a list of dicts with a single key as the form name and
    value is an integer describing that user’s form rights, where: 0=no access, 1=view records/responses and edit records (survey responses are read-only), 2=read only, and 3=edit survey responses,
filter_metadata(key)[source]

Return a list of values for the metadata key from each field of the project’s metadata.

Parameters:
key: str

A known key in the metadata structure

Returns:
filtered :

attribute list from each field

import_file(record, field, fname, fobj, event=None, repeat_instance=None, return_format='json')[source]

Import the contents of a file represented by fobj to a particular records field

Parameters:
record : str

record ID

field : str

field name where the file will go

fname : str

file name visible in REDCap UI

fobj : file object

file object as returned by open

event : str

for longitudinal projects, specify the unique event here

repeat_instance : int

(only for projects with repeating instruments/events) The repeat instance number of the repeating event (if longitudinal) or the repeating instrument (if classic or longitudinal).

return_format : (‘json’), ‘csv’, ‘xml’

format of error message

Returns:
response :

response from server as specified by return_format

import_records(to_import, overwrite='normal', format='json', return_format='json', return_content='count', date_format='YMD', force_auto_number=False)[source]

Import data into the RedCap Project

Parameters:
to_import : array of dicts, csv/xml string, pandas.DataFrame
note:If you pass a csv or xml string, you should use the format parameter appropriately.
note:Keys of the dictionaries should be subset of project’s, fields, but this isn’t a requirement. If you provide keys that aren’t defined fields, the returned response will contain an 'error' key.
overwrite : (‘normal’), ‘overwrite’

'overwrite' will erase values previously stored in the database if not specified in the to_import dictionaries.

format : (‘json’), ‘xml’, ‘csv’

Format of incoming data. By default, to_import will be json-encoded

return_format : (‘json’), ‘csv’, ‘xml’

Response format. By default, response will be json-decoded.

return_content : (‘count’), ‘ids’, ‘nothing’

By default, the response contains a ‘count’ key with the number of records just imported. By specifying ‘ids’, a list of ids imported will be returned. ‘nothing’ will only return the HTTP status code and no message.

date_format : (‘YMD’), ‘DMY’, ‘MDY’

Describes the formatting of dates. By default, date strings are formatted as ‘YYYY-MM-DD’ corresponding to ‘YMD’. If date strings are formatted as ‘MM/DD/YYYY’ set this parameter as ‘MDY’ and if formatted as ‘DD/MM/YYYY’ set as ‘DMY’. No other formattings are allowed.

force_auto_number : (‘False’) Enables automatic assignment of record IDs

of imported records by REDCap. If this is set to true, and auto-numbering for records is enabled for the project, auto-numbering of imported records will be enabled.

Returns:
response : dict, str

response from REDCap API, json-decoded if return_format == 'json'

is_longitudinal()[source]
Returns:
boolean :

longitudinal status of this project

metadata_type(field_name)[source]

If the given field_name is validated by REDCap, return it’s type

names_labels(do_print=False)[source]

Simple helper function to get all field names and labels

read_csv(buf, **df_kwargs)[source]

Wrapper around pandas read_csv that handles EmptyDataError

exception redcap.RedcapError

This is thrown when an API method fails. Depending on the API call, the REDCap server will return a helpful message. Sometimes it won’t :(

Low-Level

The Project class makes all HTTP calls to the REDCap API through the redcap.request.RCRequest class. You shouldn’t need this in day-to-day usage.

exception redcap.request.RCAPIError[source]

Errors corresponding to a misuse of the REDCap API

class redcap.request.RCRequest(url, payload, qtype, session=<requests.sessions.Session object>)[source]

Private class wrapping the REDCap API. Decodes response from redcap and returns it.

References

https://redcap.vanderbilt.edu/api/help/

Users shouldn’t really need to use this, the Project class is the biggest consumer.

__init__(url, payload, qtype, session=<requests.sessions.Session object>)[source]

Constructor

Parameters:
url : str

REDCap API URL

payload : dict

key,values corresponding to the REDCap API

qtype : str

Used to validate payload contents against API

execute(**kwargs)[source]

Execute the API request and return data

Parameters:
kwargs :

passed to requests.Session.post()

Returns:
response : list, str

data object from JSON decoding process if format==’json’, else return raw string (ie format==’csv’|’xml’)

expect_empty_json()[source]

Some responses are known to send empty responses

get_content(r)[source]

Abstraction for grabbing content from a returned response

raise_for_status(r)[source]

Given a response, raise for bad status for certain actions

Some redcap api methods don’t return error messages that the user could test for or otherwise use. Therefore, we need to do the testing ourself

Raising for everything wouldn’t let the user see the (hopefully helpful) error message

validate()[source]

Checks that at least required params exist