1. Introduction
1.1. Purpose
š This Instruction for Use provides a set of tasks required to download data from the portal.
1.2. Scope
šThis guide covers the complete lifecycle, from creation to obsolescence.
1.3. Roles and Responsibilities
Project Members and organization admins can download data through the API.
2. Procedure Description
Step 1: Get your API token
To get your API token:
-
š Navigate to the portal at https://admin.krane.one using your account.
-
š Click in the top right corner on the share icon
-
ā Copy the API token
Step 2. Calling the API
To call the API:
-
Go to https://gateway.krane.one/api-docs/#/Public to view the API docs. Here you can see which endpoint are available and which parameters you need to include in your API call to retrieve the data you are looking for.
2.2.1 Get data through Swagger
-
Click the endpoint youāre interested in (in Public section)
-
Click the lock icon in the upper right corner
-
Paste the token from the clipboard and click the Authorize button
-
Click the āTry it outā button and provide or modify parameters according to your needs
-
Click the Execute button and see the results below
-
You can download the results by clicking the Download button
2.2.2. Get data through Python
When you have the Access Token, then you can use Python to get the data you need with e.g. this code snippet:
import requests
import json
# Gets all experiments of all patients belonging to the organization.
headers = {
'authority': 'gateway.krane.one',
'accept': 'application/json',
'accept-language': 'en-US,en;q=0.9',
'referer': 'https://gateway.krane.one/api-docs/',
'authorization': 'bearer TOKEN_VALUE'
}
# enter your own token value after bearer in the authorization header (bearer as in the bearer of the token can get access)
params = {
'limit': '50',
'order': 'desc',
'sortBy': 'createdAt',
'type': 'walking' # for example. See Swagger for all experiment type options
}
# type is dependent on your data needs
# these parameters need to be aligned with the parameters that you can find in Swagger (under GET/organization/experiments)
# the parameters currently filled in work fine
response = requests.get('https://gateway.krane.one/organization/experiments', params=params, headers=headers)
print(response.json())
2.2.3. Getting results
See Swagger for all options. Typically you can use:
-
To get all data from a project: use endpoint /study/{studyId}/experiments. The study ID (project ID) can be found by editing a Project in the admin portal, see MP-05 Questionnaire Builder.
-
To get all experiment results from an organization: use endpoint /organization/experiments. This will not show experiment results from suborganizations, see below.
-
To get all experiment results from an organization including its suborganizations: use endpoint /organization/{organizationId}/experiments. The organization ID can be found by navigating to My Organization in the admin portal and is listed as the āOrganization nameā. Please note that this is not necessarily the same as the name at the top of the webpage.
-
To get all patient results on questionnaires: use endpoint /patient/{patientId}/questionnaires. The patient ID you can get from /organization/patients or through the admin portal.
2.3. Example script for individual patient's high resolution data over longer period
import requests
import pandas as pd
import datetime
import json
import math
import os
'''
This script gets all the fnirs data from a specific patient ID
'''
def get_data(patient, day, start, end, data_block, number_of_files, save):
#Enter your own token value after bearer in the authorization header
headers = {
'authority': 'gateway.krane.one',
'accept': 'application/json',
'accept-language': 'en-US,en;q=0.9',
'referer': 'https://gateway.krane.one/api-docs/',
'authorization': 'bearer TOKEN_VALUE'
}
#Initialization
df_data = pd.DataFrame() #all data will be stored in this dataframe
total_minutes = int((end-start).total_seconds()/60) #total minutes of data between start and end
n_data_block = math.ceil(total_minutes/data_block)
print(n_data_block) #check
start_date = start
#Retrieve and save data every {data_block} minutes
for n in range(n_data_block):
print(f'Current timestamp: {start_date}') #check timestamp to see when the script crashed
#Set new end date every {data_block} minutes
end_date = start_date + datetime.timedelta(minutes=data_block)
#Specify params
params = {
'startDate': start_date,
'endDate': end_date,
'patiendId': patient
}
#Get response
response = requests.get('https://gateway.krane.one/patient/{patient}/fnirs', params=params, headers=headers)
print(response,'\n') #check
#Save data as backup when response is not OK (response code 200)
if (response.status_code!=200) & (len(df_data)>0):
if save == True:
save_backup_data(day, number_of_files, df_data, start_date, n_minutes=((n + 1) * n_data_block))
#Add json data to dataframe
df = pd.DataFrame.from_dict(response.json()['data']) #create dataframe from response data
df_data = df_data.append(df, ignore_index=True) #append new data to existing df with all data stored
start_date = end_date #make previous end date the new start date
#Save data in file when end date is reached
if save == True:
save_data(day, number_of_files, df_data)
return df_data
def save_backup_data(day, number_of_files, df_data, start_date, n_minutes):
#Save data as backup
dict_data = {'data': df_data.to_dict(orient='records')}
with open(f'response_{day}_part{number_of_files}.json', 'w',
encoding='utf-8') as f:
json.dump(dict_data, f, ensure_ascii=False, indent=4)
#Print information
print(f"Response not OK after timestamp: {start_date}\n"
"Increase number_of_files by 1, and run the script again.\n"
f"Saved data of {n_minutes} minutes as response_{day}_part{number_of_files}.json")
def save_data(day, number_of_files, df_data):
dict_data = { 'data': df_data.to_dict(orient='records') }
with open(f'response_{day}_part{number_of_files}.json', 'w', encoding='utf-8') as f:
json.dump(dict_data, f, ensure_ascii=False, indent=4)
print(f"Finished saving data from {day} as response_{day}_part{number_of_files}.json\n",
f"If {number_of_files} > 1, don't forget to merge all json files together as one file.")
if __name__ == "__main__":
df_data = get_data(patient='634d48db22562d0013ab7a15',
#Manually add day, start and end date
#Round start date to start of minute, e.g. 12:15:57 = 12:15
#Round end date to next minute, e.g. 15:20:13 = 15:21
#Manually add how many minutes of data you want to get from the database per response
#Specicy whether you want to save the (backup) data
day='20feb',
start=datetime.datetime(2023, 2, 20, 8, 25),
end=datetime.datetime(2023, 2, 20, 19, 2),
data_block=20, #don't make this bigger than 25, otherwise the script crashes...
number_of_files=1, #increase by 1 if you run the script again for the same day
save=True)
2.3.1. Getting results
This scripts gets the fnirs data from the database in chunks of a specified number of minutes (default = 20 minutes), and adds all the fnirs data to one dataframe. When all data from that day is in the dataframe, it is saved as a json file.
When the connection with the server is lost, the dataframe will automatically be saved in a backup json file. Then, the script shows the timestamp of the last saved data when the connection was lost. This timestamp can be entered as new start date and the script can run again (assuming the connection is back, i.e. response.code=200).
As a user, you only need to specify the arguments in the get_data function to get all data from 1 day in json file(s).
Steps to take:
-
Copy the code above and save it as .py
-
Run the script, specify the following arguments in the get_data() function. This is also explained in the script itself:
-
day = enter the day, the output file is then named: response_<day>_part<number_of_files>.json
-
start = enter the timestamp for the start of data collection (to manually retrieve them, see: timestamp API script). Round to lowest minute, e.g. 12:15:57 = 12:15
-
end = enter the timestamp for the end of data collection (to manually retrieve them, see: timestamp API script). Round end date to highest minute, e.g. 15:20:13 = 15:21
-
data_block = enter the number of minutes of data retrieved from the database in one request. default = 20. itās recommended to not make this number bigger than 25 to avoid errors
-
number_of_files = enter the number of files that are created to retrieve the data from 1 day. default = 1
-
save = boolean value if you want to save the (backup) data. default = True
-
-
If the connection with the server is lost, the data is saved as response_<day>_part<number_of_files>.json. If this happens, enter the printed timestamp as new start, and increase number_of_files with 1. These steps are also printed when you run the script and it crashes at some point.
-
Preferably, there is only 1 file for 1 day, e.g. response_20feb_part1.json or response_28mar_part1.json.
However, if there are more parts and you want to have this in 1 json file, you can manually add these json files together in one: open part 1 ā copy part 2 ā paste in part 1 ā copy part 3 ā past in part 1 ā etc.)
For debugging:
The response code is printed every time requests.get() is called. You can make data_block very small, e.g. 1 minute, so that the script runs faster (because only 1 minute of data is retrieved from the database per request) and you can check if you have response code 200 (OK). You can also set save to False when you are debugging so that data is not saved and the script runs faster.
3. Download wearable data through API
You can download wearable data through the API as well on an organization level and for an individual user, we have specific documentation for these APIs see Swagger Krane Terra Docs
Using the same steps as in chapter 2 you can call the API and download the data. We support a variety of data types
Please note that some providers like Fitbit heavily rate limit there API; which can heavily influence the developer experience for downloading data.
While our data format is generalized over all providers it can be that some providers disclose only subsets of data. Additionally, depending of the permissions the user has given when connecting with the health data provider, some data may not be accessible.
Notes
-
Some endpoints expect a token from a user (e.g. most
/user/...endpoints) because the user ID is taken from the token. These endpoints will not work (correctly) when using the management token as generated from the management dashboard.