Getting started
Using the API
Query
Processing script example
How to use this documentation
Our goal is to break down import and querying steps into modular "puzzle pieces" that can be combined to create custom workflows. To get started, read how you can set up your programming environment, the Moveshelf API, and a GitHub repository. Then, learn how to configure the Moveshelf API and where to find a link to the complete documentation. Finally, experiment with specific examples to get started. Each example includes prerequisites that must be completed before implementation. A complete overview of this chapter's sections is available in the navigation menu on the left.
Setting up the environment
Install programs
- Visual Studio Code
- Install Python extension
- Python
- Close Visual Studio Code before installing.
- Make sure you have selected "Add to PATH" during the install process.

Run a Python script
- To run a Python script, write the following command in the terminal: python <path/to/your/script.py>, and press 'Enter'
Setting up the Moveshelf API
Installation
You can install the Moveshelf API directly via PyPI. To do so, run the following command in the terminal:- pip install moveshelf-api
Creating an access key
Before you can use the Moveshelf API, you need to create an access key:- Go to your profile page on Moveshelf (top-right corner)
- Follow instructions to generate an API key (enter ID for the new key), and click 'Generate API Key'
- Download the API key file and save 'mvshlf-api-key.json' in the root folder of your Git folder
Setting up 'mvshlf-config.json'
Additionally, you need a file called 'mvshlf-config.json', saved in the same folder as 'mvshlf-api-key.json', with the following content:{
"apiKeyFileName":"mvshlf-api-key.json",
"apiUrl":"",
"application":"None"
}
- EU region:
- StagingTesting environment used to experiment with Moveshelf's application: "https://api.staging.moveshelf.com/graphql"
- ProductionEnvironment containing clinical and/or research data. Not used for testing: "https://api.moveshelf.com/graphql"
- US region:
- Staging: "https://api.us.staging.moveshelf.com/graphql"
- Production: "https://api.us.moveshelf.com/graphql"
Your root folder should look similar to the folder below, where your processing scripts are inside a folder, e.g., 'scripts':

Setting up a GitHub repository
Clone a GitHub repository to your local machine
- Create an account on GitHub to be able to use the public repositories
- Open a public GitHub repository, e.g., moveshelf-data-examples and copy the repository URL
- Open Visual Studio Code
- Press: CTRL + Shift + P
- Type 'Git: clone’ in the top bar
- Press ‘Enter’
- Paste the repository URL and press 'Enter'


Install dependencies
To ensure your Python script runs without errors, it's best practice to list all required modules (along with their versions) in a requirements.txt file. To install these dependencies automatically:- Open a new terminal in Visual Studio Code
- Run the command: pip install -r requirements.txt in the terminal and press 'Enter'
- Make sure your terminal is in the correct folder where the requirements are saved as well.


Moveshelf API documentation
Configuration and authentication
Prerequisites
Before implementing this example, ensure that you have performed all necessary setup steps. In particular, you should have:Configure the Moveshelf API
Add the following lines of code to your processing script to use the Moveshelf API:import os, sys, json
parent_folder = os.path.dirname(os.path.dirname(__file__))
sys.path.append(parent_folder)
from moveshelf_api.api import MoveshelfApi
## Setup the API
# Load config
personal_config = os.path.join(parent_folder, "mvshlf-config.json")
if not os.path.isfile(personal_config):
raise FileNotFoundError(
f"Configuration file '{personal_config}' is missing.\n"
"Ensure the file exists with the correct name and path."
)
with open(personal_config, "r") as config_file:
data = json.load(config_file)
api = MoveshelfApi(
api_key_file=os.path.join(parent_folder, data["apiKeyFileName"]),
api_url=data["apiUrl"],
)
Basic example
Prerequisites
Before implementing this example, ensure that your processing script includes all necessary setup steps. In particular, you should have:Use built-in functions of the Moveshelf API
In this example we are going to use a built-in function of the Moveshelf API to retrieve the projects the current user has access to. Add the following line of code to get a list of all the projects that are accesible by the user:## Get available projects
projects = api.getUserProjects()
Advanced example
Prerequisites
Before implementing this example, ensure that you have performed all necessary setup steps. In particular, you should have:Extend the Moveshelf API with a custom query
If you need queries that are not included in the Moveshelf API, you can create a custom API wrapper that extends it with custom GraphQL queries. This section demonstrates how to create a custom API wrapper defining a new method (getProjectSubjectsCustom) to retrieve, for a given project, all subjects' name, ID, and metadata, and all their sessions' ID, date, and metadata.Create a custom API wrapper:
Create a new Python file (in this example we call it api.py and place it inside a folder called 'api' in the root folder), and define a subclass of MoveshelfApi (see code snippet below). This allows you to extend the existing API by adding custom GraphQL queries. For example, the built-in getProjectSubjects function only retrieves subject names and IDs. In the example below, we define getProjectSubjectsCustom, that extends the built-in getProjectSubjects function to also retrieve subject metadata and session details (ID, date, and metadata).
from moveshelf_api.api import MoveshelfApi
# Custom Moveshelf API class that extends the existing API
class MoveshelfApiCustomized(MoveshelfApi):
def getProjectSubjectsCustom(self, project_id):
data = self._dispatch_graphql(
'''
query getProjectPatients($projectId: ID!) {
node(id: $projectId) {
... on Project {
id,
name,
description,
canEdit,
patients {
id
name
metadata
sessions {
id
date
metadata
}
}
}
}
}
''',
projectId = project_id
)
return data['node']['patients']
Use the custom API in your processing script:
To use your extended API, import the custom class into your processing script. The example below shows how to call getProjectSubjectsCustom to retrieve additional metadata for all subjects and their sessions.
parentFolder = os.path.dirname(os.path.dirname(__file__))
sys.path.append(parentFolder)
from api.api import MoveshelfApiCustomized
## Setup the API
# Load config
personal_config = os.path.join(parent_folder, "mvshlf-config.json")
if not os.path.isfile(personal_config):
raise FileNotFoundError(
f"Configuration file '{personal_config}' is missing.\n"
"Ensure the file exists with the correct name and path."
)
with open(personal_config, "r") as config_file:
data = json.load(config_file)
# Use custom API
api = MoveshelfApiCustomized(
api_key_file=os.path.join(parentFolder, data["apiKeyFileName"]),
api_url=data["apiUrl"]
)
## General configuration. Set values before running the script
my_project = "<organizationName/projectName>" # e.g. support/demoProject
## Get available projects
projects = api.getUserProjects()
## Select the project
project_names = [project["name"] for project in projects if len(projects) > 0]
idx_my_project = project_names.index(my_project)
my_project_id = projects[idx_my_project]["id"]
# Custom query (defined in ../api/api.py) that extracts the metadata of all patients
# and the metadata of all their sessions within a given project
subjects = api.getProjectSubjectsCustom(my_project_id)
# Print the subject data
for subject in subjects:
print(f"Subject: {subject['name']} (ID: {subject['id']})")
print(f"Metadata: {subject['metadata']}")
print("Sessions:")
for session in subject['sessions']:
print(f" - Session {session['id']} on {session['date']} with metadata: {session['metadata']}")
Examples provided by Moveshelf
Refer to the following sections for example use cases for importing data:
Refer to the following sections for example use cases for querying data:
Create subject
- If a matching subject is found, it is retrieved
- If no existing subject is found, a new subject is created and assigned the specified MRN/EHR-ID
Prerequisites
Before implementing this example, ensure that your processing script includes all necessary setup steps. In particular, you should have:Implementation
To create a new subject or retrieve an existing one, add the following lines of code to your processing script:## README: this example shows how we can create a subject on Moveshelf
# using the Moveshelf Python API.
# For a given project (my_project), first check if there already exists
# a subject with a given MRN (my_subject_mrn). If it doesn't exist,
# we create a new subject with name my_subject_name, and assign my_subject_mrn
## General configuration. Set values before running the script
my_project = "<organizationName/projectName>" # e.g. support/demoProject
my_subject_mrn = "<subjectMRN>" # subject MRN, e.g. '1234567'
my_subject_name = "<subjectName>" # subject name, e.g. Subject1
## Get available projects
projects = api.getUserProjects()
## Select the project
project_names = [project["name"] for project in projects if len(projects) > 0]
idx_my_project = project_names.index(my_project)
my_project_id = projects[idx_my_project]["id"]
## Get the ID and name of all subjects in the project
subjects = api.getProjectSubjects(my_project_id)
## Find the subject
subject_found = False
for subject in subjects:
subject_details = api.getSubjectDetails(subject["id"])
subject_metadata = json.loads(subject_details.get("metadata", "{}"))
if my_subject_mrn == subject_metadata.get("ehr-id", None):
subject_found = True
print(
f"Found subject with name: {subject_details['name']},\n"
f"id: {subject_details['id']}, \n"
f"and MRN: {subject_metadata.get('ehr-id', None)}"
)
break
## Create new subject if there is no match
if not subject_found:
new_subject = api.createSubject(my_project, my_subject_name)
subject_updated = api.updateSubjectMetadataInfo(
new_subject["id"], json.dumps({"ehr-id": my_subject_mrn})
)
Validation
To verify that the new subject has been successfully created, you can either check directly on Moveshelf or programmatically via the Moveshelf API. For the manual validation, log in to Moveshelf and navigate to the relevant project to check if the new subject appears with the correct MRN/EHR-ID. If you prefer an automated method, add the following lines of code to your processing script, right after creating the new subject, to check the subject’s details programmatically:# Fetch subject details using the subject ID
new_subject_details = api.getSubjectDetails(new_subject["id"])
new_subject_metadata = json.loads(new_subject_details.get("metadata", "{}"))
# Print the subject details
print(f"Created subject with name: {new_subject_details['name']},\n"
f"id: {new_subject_details['id']}, \n"
f"and MRN: {new_subject_metadata.get('ehr-id', None)}")
Import subject metadata
Important: The keys in the metadata dictionary to be imported must match those used internally by Moveshelf. If you are unsure where to find the specific metadata template definition, please contact Moveshelf support for assistance.
Prerequisites
Before implementing this example, ensure that your processing script includes all necessary setup steps. In particular, you should have:Implementation
To import subject metadata to an existing subject, add the following lines of code to your processing script:## README: this example shows how we can import subject metadata to an existing
# subject on Moveshelf using the Moveshelf Python API.
# For a given project (my_project), first retrieve a subject with a given
# MRN (my_subject_mrn). Then, update subject metadata (my_subject_metadata)
## General configuration. Set values before running the script
my_project = "<organizationName/projectName>" # e.g. support/demoProject
my_subject_mrn = "<subjectMRN>" # subject MRN, e.g. '1234567'
my_subject_metadata = {
"subject-first-name": "<subjectFirstName>",
"ehr-id": my_subject_mrn,
... # Add all the fields you would like to import
} # subject metadata dictionary
## Get available projects
projects = api.getUserProjects()
## Select the project
project_names = [project["name"] for project in projects if len(projects) > 0]
idx_my_project = project_names.index(my_project)
my_project_id = projects[idx_my_project]["id"]
## Get the ID and name of all subjects in the project
subjects = api.getProjectSubjects(my_project_id)
## Find the subject
subject_found = False
for subject in subjects:
subject_details = api.getSubjectDetails(subject["id"])
subject_metadata = json.loads(subject_details.get("metadata", "{}"))
if my_subject_mrn == subject_metadata.get("ehr-id", None):
subject_found = True
# Import subject metadata
subject_updated = api.updateSubjectMetadataInfo(
subject["id"], json.dumps(my_subject_metadata)
)
break
## Print message if there was no match
if not subject_found:
print(
f"Couldn't find subject MRN: {my_subject_mrn}"
)
Validation
To verify that the subject metadata has been successfully imported, you can either check directly on Moveshelf or programmatically via the Moveshelf API. For the manual validation, log in to Moveshelf and navigate to the relevant project to check if the subject appears with the correct subject metadata. If you prefer an automated method, add the following lines of code to your processing script, right after updating subject metadata, to check the subject’s metadata programmatically:# Fetch subject details using the subject ID
subject_details = api.getSubjectDetails(subject["id"])
subject_metadata = json.loads(subject_details.get("metadata", "{}"))
# Print the subject details
print(f"Created subject with name: {subject_details['name']},\n"
f"id: {subject_details['id']}, \n"
f"and metadata: {subject_metadata}")
Download data
Moveshelf provides a public GitHub repository that contains several complete example scripts that are ready to be used.
Follow the steps in this section to run an example of querying and downloading data from the Moveshelf platform, i.e., download_data.py.
Get the public repository on your local machine
Clone Moveshelf’s public GitHub repository to your local machine. You can do this by following these steps.
Run download_data.py
- Open download_data.py in Visual Studio Code, follow the instructions, add all relevant information to the script and save the file
- To run the script, insert python scripts/download_data.py in the terminal and press 'Enter'
