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.

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_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)[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.

Returns:

data : list, str, pandas.DataFrame

exported data

export_survey_participant_list(instrument, event=None, format='json')[source]

Export the Survey Participant List

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

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
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(query, output_fields=None)[source]

Query the database and return subject information for those who match the query logic

Parameters:

query: Query or QueryGroup :

Query(Group) object to process

output_fields: list :

The fields desired for matching subjects

Returns:

A list of dictionaries whose keys contains at least the default field :

and at most each key passed in with output_fields, each dictionary :

representing a surviving row in the database. :

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, 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

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')[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.

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

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)[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)[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.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