Get in touch

Get in touch

Prefer using email? Say hi at hello@moveshelf.com

API

    Search Knowledge Base
API Usage
  • Setting up the environment
  • Python API
  • knowledgebase home

    Moveshelf is designed to keep data secure but always accessible. This is true both from our web interface, for physicians and clinical operators, as well as programmatically from our API, for engineers and scientists. This chapter contains all information to get started with the Moveshelf API, to configure your environment, to programmatically download a large amount of measurement files or to query database information about your patient population.

    Moveshelf provides two APIs to interact with its platform: a Python API and a GraphQL API. This documentation serves as a central hub for understanding and utilizing both the Python and GraphQL APIs effectively. It is designed to bridge the gap between the two APIs, offering clear guidance on their individual strengths and how they can complement each other. This documentation is intended for engineers and advanced users who want to automate workflows and build custom solutions using the APIs.
    In a nutshell, the idea is to:
    • Use the GraphQL API to explore the Moveshelf schema, understand data relationships, and write precise queries/mutations.
    • Use the Python API to execute those queries and handle operations programmatically, leveraging Python’s ecosystem for data processing and scripting.



    Setting up the environment
    To interact with the Moveshelf API, you need Python and an IDE (e.g., Visual Studio Code). This setup will allow you to run existing Python scripts from GitHub or create your own. This section walks you through setting up your environment to interact with the Moveshelf API using Python. You will install the necessary tools, clone a GitHub repository, set up dependencies, and run example scripts.
    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.



    Get the public repository on your local machine
    • Create an account on GitHub to be able to use the public repositories
    • Open the public GitHub repository 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'


  • Select a local folder where you want to clone the repository

  • Setup the dependencies
    • 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.


    Run a Python script
    • To run a python script, insert python scripts/<title of the script>.py in the terminal and press 'Enter'


     

    Python API
    The Python API simplifies integration with Moveshelf for Python developers. It abstracts authentication, request handling, and common tasks into an intuitive, high-level interface, allowing developers to focus on building solutions without needing to manage the complexities of API interactions. By offering built-in support for executing GraphQL queries and mutations, the Python API enables seamless data retrieval and manipulation while integrating naturally with Python's extensive ecosystem of libraries. This makes it an ideal choice for automating workflows, processing data, and creating custom scripts that interact with Moveshelf resources.
    • Install the Python API via PyPI: pip install moveshelf-api
    • You can find the documentation for the Python API here.

    Basic usage example: downloading data via the Python API
    Follow the steps in this section to run an existing example of querying and downloading data from the Moveshelf platform, available in the public GitHub repository.

    Run the download_data_example script
    • Follow the instructions on GitHub, starting from the ‘API Key’ step.
    • Open the download_data_example Python script in Visual Studio Code, follow the instructions, add all relevant information to the script and save the file
    • To run the script, open a terminal and execute the following command:
      python scripts/download_data_example.py


    Advanced usage example: extending the Python API with a custom query
    If you need queries that are not included in the default Python 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, andmetadata, and all their sessions' ID, date, and metadata.

    Create a custom API wrapper:
    Create a new Python file, e.g., api.py, 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, e.g., ‘download_data_example.py’. 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
    with open(os.path.join(parentFolder, "mvshlf-config.spec.json"), "r") as configFile:
        data = json.load(configFile)
    
    # And overwrite if available
    personalConfig = os.path.join(parentFolder, "mvshlf-config.json")
    if os.path.isfile(personalConfig):
        with open(personalConfig, "r") as configFile:
            data.update(json.load(configFile))
    
    # Use custom API
    api = MoveshelfApiCustomized(api_key_file=os.path.join(parentFolder, data["apiKeyFileName"]), api_url=data["apiUrl"])
    
    # ... rest of the code to access a project on Moveshelf via API ..
    
    # 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']}")