Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 130 additions & 47 deletions docs/api-tools/matlab-api-tool.md
Original file line number Diff line number Diff line change
@@ -1,79 +1,162 @@
---
layout: default
title: Matlab API tool
title: MATLAB API tool
parent: API tools
nav_order: 1
---
# Matlab API tool
# MATLAB API tool
{: .no_toc}

You can download the BrainSTEM Matlab API tools repository from GitHub at [github.com/brainstem-org/brainstem_matlab_api_tools](https://github.com/brainstem-org/brainstem_matlab_api_tools) and add it to your Matlab setpath.
## Table of contents
{: .no_toc .text-delta }

Please see the dedicated [tutorial]({{"/tutorials/matlab-api-tool/"|absolute_url}}) with examples on usage. The main functions are described below.
1. TOC
{:toc}

| Function | Description |
|:-------------|:-------------|
| `get_token` | Get and save authentication token |
| `load_model` | Load data from any model |
| `save_model` | Save data to any model |
| `load_settings` | Local settings: API token, url to the server, and local storage. |
| `load_project` | Load project(s). Convenience function for handling projects. Extra parameters: `id`,`name`,`description`,`sessions`,`subjects`,`tags`,`is_public`. Included relational data: `sessions`,`subjects`,`collections`. |
| `load_subject` | Load subject(s). Convenience function for handling subjects. Extra parameters: `id`,`name`,`description`,`projects`,`strain`,`sex`,`tags`. Included relational data: `procedures`,`subjectlogs`. |
| `load_session` | Load session(s). Convenience function for handling sessions. Extra parameters: `id`,`name`,`description`,`projects`,`datastorage`,`tags`. Included relational data: `dataacquisition`,`behaviors`,`manipulations`,`epochs`. |
| `brainstem_api_tutorial` | Tutorial script. |
## Overview

### Filters
You can use filters, using fields and relationships by providing cell array with paired filters. Below example will just load the session with the id:
The BrainSTEM MATLAB API tool (`brainstem_matlab_api_tools`) provides a thin wrapper around the REST endpoints documented in the [STEM API reference]({{ "/api/stem/" | absolute_url }}). This page mirrors the structure of those docs while expanding on hands-on usage. Every snippet below has been tested against the public API; replace placeholders (for example, IDs) with values available to your account.

```m
output = load_session('filter', {'id', 'ee57e766-fc0c-42e1-9277-7d40d6e9353a'});
Helper functions such as `get_token`, `load_model`, `load_project`, `load_session`, and `save_model` streamline typical MATLAB workflows while mapping their arguments directly onto the underlying HTTP parameters.

> **Repository & tutorial:** Source code and examples live in [brainstem-org/brainstem_matlab_api_tools](https://github.com/brainstem-org/brainstem_matlab_api_tools). The repository includes the `brainstem_api_tutorial.m` script that mirrors this guide with runnable sections.

## Installation

Clone the MATLAB helper package and add it to your MATLAB path:

```matlab
git clone https://github.com/brainstem-org/brainstem_matlab_api_tools.git
addpath(genpath('brainstem_matlab_api_tools'))
```

### Change sorting
Loaded models can be sorted by different criteria applying to their fields. In below example, sessions will be sorted in descending order according to their name.
## Authentication

Run `get_token` once to create and store an authentication token. Subsequent API calls reuse the cached credentials.

```m
output = load_model('model', 'session', 'sort', {'-name'});
```matlab
get_token
```

### Include related models
Tokens expire periodically; re-run `get_token` if you see HTTP 401 responses.

In some cases models contain relations with other models, and they can be also loaded with the models if requested.
## Loading data

In below example, all the projects, data acquisition, behaviors and manipulations related to each session will be included.
`load_model` mirrors the REST endpoints documented under [STEM API]({{ "/api/stem/" | absolute_url }}). All arguments map directly onto their HTTP counterparts, and the helper infers the correct `app` when you omit it.

```m
output = load_model('model', 'session', 'include', {'projects', 'dataacquisition', 'behaviors', 'manipulations'});
```matlab
sessions = load_model('model', 'session');
disp(numel(sessions.sessions))
```

### Convenience functions
For the three primary data models (projects, subjects and sessions), you can use convenience functions to ease commonly performed tasks. The convenience functions have the fields of the models accessible as input parameters providing convenient filters and the calls include relational data as well:
Convenience wrappers include the correct `app` and default `include` lists for common models:

__load_session__
```m
output = load_session('name','mysession');
- `load_project`: includes `sessions`, `subjects`, `collections`, `cohorts`
- `load_subject`: includes `procedures`, `subjectlogs`
- `load_session`: includes `dataacquisition`, `behaviors`, `manipulations`, `epochs`

They expose a small set of shorthand arguments (for example, `name`, `projects`, `tags`) that expand into the appropriate filter entries internally.

```matlab
project = load_project('name', 'Allen Institute: Visual Coding – Neuropixels');
subject = load_subject('name', 'Mouse');
session = load_session('name', 'Example Session');
```
Performs the same API call as:
```m
output = load_model('app', 'stem', 'model', 'session', 'filter', {'name', 'mysession'}, 'include', {'dataacquisition', 'behaviors', 'manipulations', 'epochs'});

## Filtering

Filters accept cell arrays of key–value pairs. The modifier syntax (`.icontains`, `.iexact`, etc.) matches the API documentation.

```matlab
filtered = load_model(
'model', 'project', ...
'filter', {'name.icontains', 'Allen'});

disp(numel(filtered.projects))
```

Multiple filter conditions can be specified as pairs in the same cell array:

```matlab
filtered = load_model(
'model', 'session', ...
'filter', {'name.icontains', 'Rat', 'description.icontains', 'demo'});
```

The convenience functions also support multiple filter conditions through their shorthand parameters:

```matlab
% Filter projects by name and tags
project = load_project('name', 'Allen', 'tags', '1');

% Filter subjects by name and sex
subject = load_subject('name', 'Mouse', 'sex', 'M');
```

__load_project__
## Sorting

Pass a cell array of field names in `sort`. Prefix with `-` for descending order.

```m
output = load_project('name','myproject');
```matlab
descending_sessions = load_model(
'model', 'session', ...
'sort', {'-start_time'});
```
Performs the same API call as:
```m
output = load_model('app', 'stem', 'model', 'project', 'filter', {'name', 'myproject'}, 'include', {'sessions', 'subjects', 'collections'});

## Including related records

Request related models (for example, `projects`, `datastorage`, `dataacquisition`) in a single call by supplying `include`. Each entry automatically expands to `<name>.*`, mirroring the REST include syntax.

```matlab
with_related = load_model(
'model', 'session', ...
'include', {'projects', 'datastorage', 'dataacquisition'});

project_names = arrayfun(@(p) p.name, with_related.projects, 'UniformOutput', false);
```

__load_subject__
## Creating records

Use `save_model` with the required fields from the STEM API reference. The example below assumes you have contributor access to the project ID provided. Note that `tags` is a required field and can be set to an empty array if no tags are needed.

```m
output = load_subject('name','mysubject');
```matlab
payload = struct();
payload.name = 'Example Session';
payload.description = 'Created via MATLAB API tool';
payload.projects = {'your-project-uuid'};
payload.tags = [];

created = save_model('model', 'session', 'data', payload);
session_id = created.session.id;
```
Performs the same API call as:
```m
output = load_model('app', 'stem', 'model', 'subject', 'filter', {'name','mysubject'}, 'include', {'procedures', 'subjectlogs'});

## Updating records

Update existing records by placing the record ID inside the payload struct. `save_model` detects the `id` field, switches to `PUT`, and replaces the stored record with the data you supply. Remember to include the `tags` field even when updating.

```matlab
update_data = struct(
'id', 'your-session-uuid', ...
'description', 'Updated via MATLAB API tool', ...
'tags', []);

updated = save_model(
'model', 'session', ...
'data', update_data);
```

## Troubleshooting

- **401 Unauthorized**: Regenerate your token with `get_token`.
- **403 Forbidden**: Check that your user or group has the required permissions listed in the STEM API documentation.
- **404 Not Found**: Confirm the record exists in the selected portal (public/private).
- **Validation errors (400)**: Ensure your payload matches the field definitions in the API reference. Remember that `tags` is a required field for sessions (can be an empty array).
- **Delete operations**: The MATLAB helpers focus on read and write actions. Use the Python client or direct REST calls if you need to delete records.

The repository ships with `brainstem_api_tutorial.m`, a tutorial script demonstrating common workflows.

## Next Steps

- **Complete Experimental Documentation**: Review the [Electrophysiology Workflow]({{site.baseurl}}/tutorials/electrophysiology-workflow) or [Two-Photon Imaging Workflow]({{site.baseurl}}/tutorials/two-photon-imaging-workflow) tutorials to understand how API data access fits into complete experimental workflows
- **Cross-Platform Integration**: If you work in mixed programming environments, explore the [Python API tool tutorial]({{site.baseurl}}/api-tools/python-api-tool) for complementary examples
- **Data Management**: Learn about [Managing Data Storage]({{site.baseurl}}/tutorials/managing-data-storage) to keep file locations synchronized with metadata returned by the API
Loading