Get a demo

Get in touch

Prefer using email? Write us at hello@moveshelf.com

Developer – Extending the Moveshelf API

    Search Knowledge Base
Getting started
  • Setting up the environment
  • Setting up a GitHub repository
  • Setting up the Moveshelf API
  • Recording - Intro to Moveshelf API
  • Using the API
  • Moveshelf API documentation
  • Configuration and authentication
  • Use built-in functions
  • Examples provided by Moveshelf
  • Importing data
  • Create subject
  • Import subject metadata
  • Create session
  • Import session metadata
  • Create trial
  • Upload data files
  • Create interactive reports
  • Querying data
  • Retrieve a filtered subset of subjects
  • Retrieve a filtered subset of sessions
  • Retrieve a subject
  • Retrieve subject metadata
  • Retrieve session
  • Retrieve session metadata
  • Export metadata to Excel
  • Retrieve trials
  • Retrieve data files
  • Deleting data
  • Delete a subject
  • Delete multiple subjects
  • Delete a session
  • Delete a trial
  • Delete all trials within a condition
  • Delete a data file
  • Example scripts
  • Public repository
  • Download data
  • Download large data sets
  • Batch upload data
  • Pre vs post intervention data export
  • Extending the Moveshelf API
  • Extending the Moveshelf API
  • How to extend the Moveshelf API for advanced and custom use cases.



    Extending the Moveshelf API
    In this section we will show how you can adapt the Moveshelf API to your own use cases by implementing your own functions.
    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 (getProjectSubjectsWithAdditionalData) 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 getProjectSubjectsWithAdditionalData, that extends the built-in getProjectSubjects function to also retrieve subject metadata, session details (ID, date, and metadata) and URLs for additional data (i.e., files).

    from moveshelf_api.api import MoveshelfApi
    
    # Custom Moveshelf API class that extends the existing API
    
    class MoveshelfApiCustomized(MoveshelfApi):
    
        def getProjectSubjectsWithAdditionalData(self, project_id: str):
            data = self._dispatch_graphql(
                '''
                query getProjectPatients($projectId: ID!) {
                    node(id: $projectId) {
                        ... on Project {
                            id
                            name
                            description
                            configuration
                            canEdit
                            template {
                                name
                                data
                            }
                            patients {
                                id
                                name
                                metadata
                                project {
                                    id
                                }
                                sessions {
                                    id
                                    date
                                    projectPath
                                    clips {
                                        id
                                        title
                                        created
                                        projectPath
                                        uploadStatus
                                        hasCharts
                                        additionalData {
                                            id
                                            dataType
                                            uploadStatus
                                            originalFileName
                                            originalDataDownloadUri
                                        }
                                    }
                                }
                            }
                            norms {
                                id
                                projectPath
                            }
                        }
                    }
                }
                ''',
                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 getProjectSubjectsWithAdditionalData to retrieve metadata for all subjects and their sessions.

    parent_folder = os.path.dirname(os.path.dirname(__file__))
    sys.path.append(parent_folder)
    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(parent_folder, 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.getProjectSubjectsWithAdditionalData(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']}")