Skip to content

API examples

Jon Clucas edited this page Aug 2, 2018 · 19 revisions

In this set of example code blocks, variables may not be assigned on this page or may be assigned in examples earlier on the page.

Login/Sign up User

login

For most API connections, the authToken.token string provided at login is required for subsequent actions.

var which_girder = "dev"
fetch('config.json')
  .then(response => response.json())
  .then(jsonResponse => {
    window.host = jsonResponse["girder-"+which_girder]["host"]
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var auth_response = this.responseText;
        window.authToken = JSON.parse(auth_response)["authToken"]["token"]
        console.log(auth_response);
      }
    });
    xhr.open("GET", "http://" + host + "/api/v1/user/authentication", true);
    xhr.setRequestHeader("Girder-Authorization", "Basic " + btoa(jsonResponse["girder-"+which_girder]["user"] + ":" + jsonResponse["girder-"+which_girder]["password"]));
    xhr.send( null );
});

The Python API client handles the authToken implicitly.

import girder_client as gc
girder_connection = gc.GirderClient(
    apiUrl='http://mindlogger-girder-atlas.a4vwd5q7ib.us-east-1.elasticbeanstalk.com/api/v1'
)
girder_connection.authenticate(
    username=username,
    password=password,
    apiKey=apiKey
)

sign up

password supplied

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});
var data = new FormData();
data.append('login', username);
data.append('email', email);
data.append('firstName', firstname);
data.append('lastName', lastname);
data.append('password', password);
data.append('admin', false);
data.append('token', window.authToken);
xhr.open("POST", "http://" + window.host + "/api/v1/user", true);
xhr.send(data);
girder_connection.post(
    "&".join([
        "user?login={}".format(username),
        "email={}".format(email),
        "firstName={}".format(firstname),
        "lastName={}".format(lastname),
        "password='{}'".format(password),
        "admin=false"
    ])
) # create new user

no password supplied

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
    xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });
    data = new FormData();
    data.append('email', email);
    xhr.open("PUT", "http://" + jsonResponse["girder-dev"]["host"] + "/api/v1/user/password/temporary", true);
    xhr.send(data);
  }
});
var data = new FormData();
data.append('login', username);
data.append('email', email);
data.append('firstName', firstname);
data.append('lastName', lastname);
data.append('password', (crypto.getRandomValues(new Uint32Array(1))*12).toString());
data.append('admin', false);
data.append('token', window.authToken);
xhr.open("POST", "http://" + window.host + "/api/v1/user", true);
xhr.send(data);
import random
import string
girder_connection.post(
    "&".join([
        "user?login={}".format(username),
        "email={}".format(email),
        "firstName={}".format(firstname),
        "lastName={}".format(lastname),
        "password='{}'".format(
            "".join(
                random.sample(
                    string.printable,
                    28
                )
            )
        ), # random password
        "admin=false"
    ])
) # create new user
girder_connection.put(
    "user/password/temporary?email={}".format(
        email
    )
) # send temporary password

Assign user role from admin user, invite user

assign role

Assign a user to the "Viewers" group

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var group = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var users = JSON.parse(this.responseText);
        for (var i = 0; i < users.length; i++) {
          if (users[i]["email"] == email) {
            var user = users[i]["_id"];
          }
        }
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText)
          }
        });
        var data = new FormData();
        data.append('userId', user);
        data.append('quiet', true);
        data.append('force', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/group/" + group + "/invitation");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/user?text=" + email, true);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/group?text=Viewers&exact=True", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);

pull all groups and users in an API call

role = "Viewers"
groups = girder_connection.get(
    "group"
) # get all groups
role_id = [
    group for group in groups if group['name']==role
][0]["_id"] # get Girder_id for "Viewers" group
users = girder_connection.get("user")
user_id = [
    user for user in users if user['email']==email
][0]["_id"] # get Girder_id for user
girder_connection.post(
    "".join([
        "group/{}".format(role_id),
        "/invitation?userId={}".format(user_id),
        "&quiet=true&force=true"
    ])
)

pull specific groups and users in an API call

role = "Viewers"
role_id = girder_connection.get(
    "group?text={}".format(role)
)[0]["_id"]
user_id = girder_connection.get(
    "user?email={}".format(email)
)[0]["_id"]
girder_connection.post(
    "".join([
        "group/{}".format(role_id),
        "/invitation?userId={}".format(user_id),
        "&quiet=true&force=true"
    ])
)

invite user

Invite user to "Users" group:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var group = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var users = JSON.parse(this.responseText);
        for (var i = 0; i < users.length; i++) {
          if (users[i]["email"] == email) {
            var user = users[i]["_id"];
          }
        }
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText)
          }
        });
        var data = new FormData();
        data.append('userId', user);
        data.append('quiet', false);
        data.append('force', false);
        xhr.open("POST", "http://" + window.host + "/api/v1/group/" + group + "/invitation");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/user?text=" + email, true);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/group?text=Users&exact=True", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.post(
    "".join([
        "group/{}".format(role_id),
        "/invitation?userId={}".format(user_id),
        "&quiet=false&force=false"
    ])
)

CRUD volumes

create volumes

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText)
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
volumes_id = girder_connection.get(
    "collection?text=Volumes"
)[0]["_id"]
girder_connection.post(
    "&".join([
        "folder?name={}".format(volume_name),
        "parentId={}".format(volumes_id),
        "parentType=collection",
        "reuseExisting=true"
    ])
)

read volumes

List folders in a Volume

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)[0]["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText)
          }
        });
        xhr.open("GET", "http://" + window.host + "/api/v1/folder?parentType=folder&parentId=" + volume_id);
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(null);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/folder?parentType=collection&parentId=" + volumes_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.get(
    "&".join([
        "folder?parentType=folder&parentId={}".format(
            girder_connection.get(
                "&".join([
                    "folder?parentType=collection",
                    "parentId={}".format(volumes_id),
                    "text={}".format(volume_name)
                ])
            )[0]["_id"]
        )
    ])
) # list folders in Volume

update volumes

Make Volume's status inactive

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)[0]["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText)
          }
        });
        var data = new FormData();
        data.append('metadata', JSON.stringify({'status': 'inactive'}));
        xhr.open("PUT", "http://" + window.host + "/api/v1/folder/" + volume_id);
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/folder?parentType=collection&parentId=" + volumes_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
import json
girder_connection.put(
    "folder/{}".format(
        girder_connection.get(
            "&".join([
                "folder?parentType=collection",
                "parentId={}".format(volumes_id),
                "text={}".format(volume_name)
            ])
        )[0]["_id"]
    ),
    parameters={
        "metadata": json.dumps(
            {'status': 'inactive'}
        )
    }
) # make volume's status inactive

delete volumes

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)[0]["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText)
          }
        });
        xhr.open("DELETE", "http://" + window.host + "/api/v1/folder/" + volume_id);
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(null);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/folder?parentType=collection&parentId=" + volumes_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.delete(
    "folder/{}".format(
        girder_connection.get(
            "&".join([
                "folder?parentType=collection",
                "parentId={}".format(volumes_id),
                "text={}".format(volume_name)
            ])
        )[0]["_id"]
    )
)

CRUD activities in volume

create activity

var now = new Date().toISOString();
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var activities_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                var activity_id = JSON.parse(this.responseText)["_id"];
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.addEventListener("readystatechange", function () {
                  if (this.readyState === 4) {
                    var my_id = JSON.parse(this.responseText)["_id"];
                    var xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.addEventListener("readystatechange", function () {
                      if (this.readyState === 4) {
                        console.log(this.responseText);
                      }
                    });
                    var data = new FormData();
                    data.append('name', activity_name + " (" + now.substring(0,10) + ")");
                    data.append('parentId', activity_id);
                    data.append('parentType', 'folder');
                    data.append('reuseExisting', true);
                    data.append('metadata', JSON.stringify({
                                '@context': {
                                    "@base": "http://localhost:8080/api/v1/",
                                    "devices": "http://www.w3id.org/abdn/irp/devices/",
                                    "nidm": "http://nidm.nidash.org/specs/nidm-experiment.html#",
                                    "oslc": "http://open-services.net/ns/core#",
                                    "pav": "http://purl.org/pav/",
                                    "pav:lastUpdatedOn": {
                                        "@type": "xsd:dateTime"
                                    },
                                    "schema": "http://schema.org/",
                                    "schema:description": {
                                        "@type": "xsd:string"
                                    },
                                    "schema:name": {
                                        "@type": "xsd:string"
                                    },
                                    "xsd": "http://www.w3.org/2001/XMLSchema"
                                },
                                "oslc:modifiedBy": [
                                    {
                                        "@id": "user/" + my_id
                                    }
                                ],
                                "pav:lastUpdatedOn": now,
                                "schema:name": {
                                    "@language": "en-US",
                                    "@value": activity_name
                                }
                              }));
                    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
                    xhr.setRequestHeader("Girder-Token", window.authToken);
                    xhr.send(data);
                      }
                    });
                xhr.open("GET", "http://" + window.host + "/api/v1/user/me");
                xhr.setRequestHeader("Girder-Token", window.authToken);
                xhr.send(null);
              }
            });
            var data = new FormData();
            data.append('name', activity_name);
            data.append('parentId', activities_id);
            data.append('parentType', 'folder');
            data.append('reuseExisting', true);
            xhr.open("POST", "http://" + window.host + "/api/v1/folder");
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data);
          }        
        });
        var data = new FormData();
        data.append('name', "Activities");
        data.append('parentId', volume_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
from datetime import datetime
import json
import tzlocal
from urllib.parse import quote

activities_id = girder_connection.post(
    "&".join([
        "folder?name=Activities",
        "parentId={}".format(volume_id),
        "parentType=folder",
        "reuseExisting=true"
    ])
)["_id"] # create or find the Activities Folder in the relevant Volume; store the _id to a variable

activity_id = girder_connection.post(
    "&".join([
        "folder?name={}".format(activity_name),
        "parentId={}".format(activities_id),
        "parentType=folder",
        "reuseExisting=true"
    ])
)["_id"] # create or find the Activity Folder in the relevant Volume.Activities; store the _id to a variable

activity_version_id = girder_connection.post(
    "&".join([
        "folder?name={}".format(
            "{} ({})".format(
                activity_name,
                date.today().strftime("%F")
            )
        ),
        "folderId={}".format(activity_id),
        "reuseExisting=true",
        "metadata={}".format(
            quote(
                json.dumps(
                    {
                        "@context": {
                            "@base": "http://localhost:8080/api/v1/",
                            "devices": "http://www.w3id.org/abdn/irp/devices/",
                            "nidm": "http://nidm.nidash.org/specs/nidm-experiment.html#",
                            "oslc": "http://open-services.net/ns/core#",
                            "pav": "http://purl.org/pav/",
                            "pav:lastUpdatedOn": {
                                "@type": "xsd:dateTime"
                            },
                            "schema": "http://schema.org/",
                            "schema:description": {
                                "@type": "xsd:string"
                            },
                            "schema:name": {
                                "@type": "xsd:string"
                            },
                            "xsd": "http://www.w3.org/2001/XMLSchema"
                        },
                        "oslc:modifiedBy": [
                            {
                                "@id": "user/{}".format(
                                    girder_connection.get(
                                        "user/me"
                                    )["_id"]
                                )
                            }
                        ],
                        "pav:lastUpdatedOn": datetime.now(
                            tzlocal.get_localzone()
                        ).strftime("%FT%T.%f%z"),
                        "schema:name": {
                            "@language": "en-US",
                            "@value": activity_name
                        }
                    }
                )
            )
        )
    ])
)["_id"] # create a version Folder of the Activity in the Activity Folder; store the _id to a variable

read activity

list Folders (Activity versions) within a named Activity Folder

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var activities_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                var activity_id = JSON.parse(this.responseText)["_id"];
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.addEventListener("readystatechange", function () {
                  if (this.readyState === 4) {
                    console.log(this.responseText);
                  }
                });
                xhr.open("GET", "http://" + window.host + "/api/v1/folder?parentType=folder&parentId=" + activity_id);
                xhr.setRequestHeader("Girder-Token", window.authToken);
                xhr.send(null);
              }
            });
            var data = new FormData();
            data.append('parentType', 'folder');
            data.append('parentId', activities_id);
            data.append('name', activity_name);
            data.append('reuseExisting', true);
            xhr.open("POST", "http://" + window.host + "/api/v1/folder");
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data);
          }
        });
        var data = new FormData();
        data.append('name', "Activities");
        data.append('parentId', volume_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
activities_id = girder_connection.get(
    "&".join([
        "folder?parentType=folder",
        "parentId={}".format(
            girder_connection.get(
                "&".join([
                    "folder?parentType=collection",
                    "parentId={}".format(volumes_id),
                    "text={}".format(volume_name)
                ])
            )[0]["_id"]
        ),
        "name={}".format(
            "Activities"
        )
    ])
)[0]["_id"] # get "Activities" _id within Volume
activity_id = girder_connection.get(
    "&".join([
        "folder?parentType=folder",
        "parentId={}".format(
            activities_id
        ),
        "name={}".format(
            activity_name
        )
    ])
)[0]["_id"] # get _id of named Activity
girder_connection.get(
    "item?folderId={}".format(
        activity_id
    )
) # list Items (versions) within Activity

load an image from an Activity's first Screen

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var activities_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                var activity_id = JSON.parse(this.responseText)["_id"];
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.addEventListener("readystatechange", function () {
                  if (this.readyState === 4) {
                    var activity_version_id = JSON.parse(this.responseText)["_id"];
                    var xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.addEventListener("readystatechange", function () {
                      if (this.readyState === 4) {
                        var item_id = JSON.parse(this.responseText)[0]["_id"]; // get first Item in Activity Version Folder
                        var xhr = new XMLHttpRequest();
                        xhr.withCredentials = true;
                        xhr.addEventListener("readystatechange", function () {
                          if (this.readyState === 4) {
                            var image = JSON.parse(this.responseText)[0];
                            document.getElementById("image").src = "http://" + window.host + "/api/v1/file/" + image["_id"] + "/download?contentDisposition=inline";
                          }
                        });
                        xhr.open("GET", "http://" + window.host + "/api/v1/item/" + item_id + "/files");
                        xhr.setRequestHeader("Girder-Token", window.authToken);
                        xhr.send(null);
                      }
                    });
                    xhr.open("GET", "http://" + window.host + "/api/v1/item?folderId=" + activity_version_id);
                    xhr.setRequestHeader("Girder-Token", window.authToken);
                    xhr.send(null);
                  }
                });
                var data = new FormData();
                data.append('parentId', activity_id);
                data.append('parentType', 'folder');
                data.append('name', activity_version);
                data.append('reuseExisting', true);
                xhr.open("POST", "http://" + window.host + "/api/v1/folder");
                xhr.setRequestHeader("Girder-Token", window.authToken);
                xhr.send(data);
              }
            });
            var data = new FormData();
            data.append('parentType', 'folder');
            data.append('parentId', activities_id);
            data.append('name', activity_name);
            data.append('reuseExisting', true);
            xhr.open("POST", "http://" + window.host + "/api/v1/folder");
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data);
          }
        });
        var data = new FormData();
        data.append('name', "Activities");
        data.append('parentId', volume_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
from IPython.display import Image

activity_version_id = girder_connection.get(
    "&".join([
        "folder?parentId={}".format(
            activity_id
        ),
        "parentType=folder"
    ])
)[0]["_id"]
screen_id = girder_connection.get(
    "item?folderId={}".format(activity_version_id)
)[0]["_id"] # get Activity's first Screen's _id
girder_connection.downloadFile(
    fileId=girder_connection.get(
        "item/{}/files".format(screen_id)
    )[0]["_id"],
    path=os.path.join(
        os.getcwd(),
        girder_connection.get(
            "item/{}/files".format(screen_id)
        )[0]["name"]
    )
) # download the Image
Image(
    filename=os.path.join(
        os.getcwd(),
        girder_connection.get(
            "item/{}/files".format(screen_id)
        )[0]["name"]
    )
) # display the Image

update activity

create a default sequence of screens

In this example, the default sequence is a sequence of three screens in a list or array that excludes the second screen, which presumably is conditional on a response in the first screen.

// In this example,:
// - `activity_version_id` is a string Girder _id for an Activity Version Folder
// - `ingredients` is an Array of strings, names of screens in sequence.
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var activity_version_meta = JSON.parse(this.responseText)["meta"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var screens = JSON.parse(this.responseText);
        activity_version_meta.screens = [];
        for (var i=0; i < ingredients.length; i++){
          for (var j=0; j < screens.length; j++){
            if(screens[j]["name"]==ingredients[i]){
              activity_version_meta.screens.push({"@id": "item/" + screens[j]["_id"]});
            }
          }
        }
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText);
          }
        });
        var data = new FormData();
        data.append('metadata', JSON.stringify(activity_version_meta));
        xhr.open("PUT", "http://" + window.host + "/api/v1/folder/" + activity_version_id);
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/item?folderId=" + activity_version_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/folder/" + activity_version_id);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
meta = girder_connection.get(
    "item/{}".format(activity_version_id)
)["meta"]

meta["screens"] = [
    {
        "@id": "item/{}".format(screens_ids[0])
    },
    {
        "@id": "item/{}".format(screens_ids[2])
    },
    {
        "@id": "item/{}".format(screens_ids[3])
    }
]

girder_connection.put(
    "?".join([
        "folder/{}".format(activity_version_id),
        "metadata={}".format(
            quote(
                json.dumps(
                    meta # dictionary
                )
            )
        )
    ])
)

rename, move, and update metadata

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var activity_version = JSON.parse(this.responseText);
    var activity_version_meta = activity_version["meta"];
    var activity_id = activity_version["parentId"];
    activity_version_meta["schema:name"]["@value"] = new_name; // update name in metadata
    var im_in = false;
    for (var i=0; i < activity_version_meta["oslc:modifiedBy"].length; i++) {
      if (activity_version_meta["oslc:modifiedBy"][i]["@id"] == "user/"+my_id) {
        im_in = true;
      }
    }
    if (!im_in) {
      activity_version_meta["oslc:modifiedBy"].push({"@id": "user/"+my_id}); // add self to list of modifying users if not already included
    };
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var activities_id = JSON.parse(this.responseText)["parentId"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var new_activity_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                console.log(this.responseText);
              }
            });
            var data = new FormData();
            data.append('metadata', JSON.stringify(activity_version_meta)); // update metadata
            data.append('name', new_name + ' (' + now.substring(0,10) + ')'); // rename activity version
            data.append('parentId', new_activity_id); // move to new parent folder
            data.append('parentType', 'folder');
            data.append('reuseExisting', true);
            xhr.open("PUT", "http://" + window.host + "/api/v1/folder/" + activity_version_id);
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data); 
          }
        });
        var data = new FormData();
        data.append('parentId', activities_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        data.append('name', new_name);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    xhr.open("GET", "http://" + window.host + "/api/v1/folder/"+activity_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/folder/" + activity_version_id);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
meta = girder_connection.get(
    "folder/{}".format(activity_version_id)
)['meta'] # get existing metadata
meta['schema:name']["@value"] = new_name # set new name in metadata
meta['oslc:modifiedBy'] = [
    {
        "@id": "user/{}".format(user_id) 
    } for user_id in set(
        user["@id"] for user in meta['oslc:modifiedBy']
    )
] # add self to list of modifying users if not already included
meta['pav:lastUpdatedOn'] = datetime.now(
    tzlocal.get_localzone()
).strftime("%FT%T.%f%z") # set lastUpdatedOn to now
girder_connection.put(
    "&".join([
        "folder/{}?name={}".format(
            activity_version_id,
            "{} ({})".format(
                new_name,
                date.today().strftime("%F")
            )
        ), # rename activity version
        "parentType=folder",
        "parentId={}".format(
            girder_connection.post(
                "&".join([
                    "folder?parentId={}".format(
                        activities_id
                    ),
                    "parentType=folder",
                    "name={}".format(
                        new_name
                    ),
                    "reuseExisting=true"
                ])
            )["_id"]
        ), # move to new_name activity folder, creating if not exists
        "metadata={}".format(quote(json.dumps(meta))), # update metadata,
        "reuseExisting=true"
    ])
)

upload a File to an Activity

function handleFileSelect(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  var fileObject = evt.dataTransfer.files[0]; // FileList object item 0.
  var activity_version_id = window.activity_version_id;
  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;
  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
      var parentItem = JSON.parse(this.responseText)["_id"];
      var reader = new FileReader();
      reader.onloadend = function () {
          
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var upload = JSON.parse(this.response);
            console.log(upload);        
          }
        });
        xhr.open("POST", "http://" + window.host + "/api/v1/file?name=" + fileObject.name + "&size=" + fileObject.size + "&mimeType=" + fileObject.type + "&parentType=item&parentId=" + parentItem);
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(fileObject);
      }
      reader.readAsBinaryString(fileObject);
    }
  });
  var data = new FormData();
  data.append('name', 'Images');
  data.append('folderId', activity_version_id);
  data.append('reuseExisting', true);
  xhr.open("POST", "http://" + window.host + "/api/v1/item");
  xhr.setRequestHeader("Girder-Token", window.authToken);
  xhr.send(data);
}


function handleDragOver(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

var dropZone = document.createElement('div');
dropZone.appendChild(document.createTextNode('Drop file here'));
var output = document.createElement('output');
output.setAttribute('id', 'list');
dropZone.append(output);
dropZone.setAttribute('id', 'drop_zone');
element.append(dropZone);
// Setup the dnd listeners.
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
from urllib.request import urlopen

image_stream = urlopen(url_or_filepath) # url_or_filepath includes protocol, eg, "https://", "file://", "ftp://"

img_id = girder_connection.uploadFile(
    parentId=girder_connection.post(
        "&".join([
            "item?folderId={}".format(activity_version_id),
            "name=Images",
            "reuseExisting=true"
        ])
    )["_id"], # create or find "Images" Item in Activity Version Folder
    parentType="item",
    stream=image_stream,
    name=".".join([
        new_name,
        image_stream.info()["Content-Type"].split("/")[-1]
    ]), # name to save the File as in Mindlogger, including extension
    size=int(
        image_stream.info()["Content-Length"]
    ) # size of the File in bytes
)["_id"]

delete activity

delete activity version

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var activities_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                var activity_id = JSON.parse(this.responseText)["_id"];
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.addEventListener("readystatechange", function () {
                  if (this.readyState === 4) {
                    var activity_version_id = JSON.parse(this.responseText)["_id"];
                    var xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.addEventListener("readystatechange", function () {
                      if (this.readyState === 4) {
                        console.log(this.response);
                      }
                    });
                    xhr.open("DELETE", "http://" + window.host + "/api/v1/folder/" + activity_version_id);
                    xhr.setRequestHeader("Girder-Token", window.authToken);
                    xhr.send(null);
                  }
                });
                var data = new FormData();
                data.append('parentId', activity_id);
                data.append('parentType', 'folder');
                data.append('name', activity_version);
                data.append('reuseExisting', true);
                xhr.open("POST", "http://" + window.host + "/api/v1/folder");
                xhr.setRequestHeader("Girder-Token", window.authToken);
                xhr.send(data);
              }
            });
            var data = new FormData();
            data.append('parentType', 'folder');
            data.append('parentId', activities_id);
            data.append('name', activity_name);
            data.append('reuseExisting', true);
            xhr.open("POST", "http://" + window.host + "/api/v1/folder");
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data);
          }
        });
        var data = new FormData();
        data.append('name', "Activities");
        data.append('parentId', volume_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.delete(
    "folder/{}".format(activity_version_id)
)

delete activity folder

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var volumes_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var volume_id = JSON.parse(this.responseText)["_id"];
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            var activities_id = JSON.parse(this.responseText)["_id"];
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === 4) {
                var activity_id = JSON.parse(this.responseText)["_id"];
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.addEventListener("readystatechange", function () {
                  if (this.readyState === 4) {
                    console.log(this.response);
                  }
                });
                xhr.open("DELETE", "http://" + window.host + "/api/v1/folder/" + activity_id);
                xhr.setRequestHeader("Girder-Token", window.authToken);
                xhr.send(null);
              }
            });
            var data = new FormData();
            data.append('parentType', 'folder');
            data.append('parentId', activities_id);
            data.append('name', activity_name);
            data.append('reuseExisting', true);
            xhr.open("POST", "http://" + window.host + "/api/v1/folder");
            xhr.setRequestHeader("Girder-Token", window.authToken);
            xhr.send(data);
          }
        });
        var data = new FormData();
        data.append('name', "Activities");
        data.append('parentId', volume_id);
        data.append('parentType', 'folder');
        data.append('reuseExisting', true);
        xhr.open("POST", "http://" + window.host + "/api/v1/folder");
        xhr.setRequestHeader("Girder-Token", window.authToken);
        xhr.send(data);
      }
    });
    var data = new FormData();
    data.append('name', volume_name);
    data.append('parentType', 'collection');
    data.append('parentId', volumes_id);
    data.append('reuseExisting', true);
    xhr.open("POST", "http://" + window.host + "/api/v1/folder");
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(data);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/collection?text=Volumes", true);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.delete(
    "folder/{}".format(folder_id)
)

CRUD screens in activity

create screen

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.response);
  }
});
var data = new FormData();
data.append('folderId', activity_version_id);
data.append('name', screen_name);
data.append('reuseExisting', true);
data.append('metadata', JSON.stringify({
  '@context': {
    "@base": "http://localhost:8080/api/v1/",
    "devices": "http://www.w3id.org/abdn/irp/devices/",
    "nidm": "http://nidm.nidash.org/specs/nidm-experiment.html#",
    "oslc": "http://open-services.net/ns/core#",
    "pav": "http://purl.org/pav/",
    "pav:lastUpdatedOn": {
      "@type": "xsd:dateTime"
    },
    "schema": "http://schema.org/",
    "schema:description": {
      "@type": "xsd:string"
    },
    "schema:name": {
      "@type": "xsd:string"
    },
    "xsd": "http://www.w3.org/2001/XMLSchema"
  },
  "oslc:modifiedBy": [
    {
      "@id": "user/" + my_id
    }
  ],
  "pav:lastUpdatedOn": now,
  "schema:name": {
    "@language": "en-US",
    "@value": screen_name
  }
}));
xhr.open("POST", "http://" + window.host + "/api/v1/item");
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(data);
screen_id = girder_connection.post(
    "&".join([
        "item?name={}".format(
            screen_name
        ),
        "folderId={}".format(activity_version_id),
        "reuseExisting=true",
        "metadata={}".format(
            quote(
                json.dumps(
                    meta # dictionary
                )
            )
        )
    ])
)["_id"] # create a Screen in the Activity Folder; store the _id to a variable

read & update screen

add conditional logic based on option values

In this example, screens_ids is a list or array of Girder_id strings pointing to screens. After reading each option in the first screen, we add a 'next_screen' entry (pointing to the second screen) to each option whose value is not None. For options with value None, the current 'next_screen' entry is kept if one exists, otherwise the next screen in the default sequence follows the first question in screens_ids.

// In this example:
// - `screen` is a predefined object (Girder Screen Item)
// - `option_value` is the value to send to the next screen
// - `next_screen` is a string Girder _id for the next screen
var xhr = new XMLHttpRequest();
if (screen.meta.hasOwnProperty("options")) {
  for (var j=0; j < screen.meta.options.length; j++) {
    if (screen.meta.options[j].value == option_value){
      screen.meta.options[j]["next_screen"] = {"@id":"item/"+next_screen};
    }
  }
} else {
  screen.meta.options = [
    {
      "option_text": {
        "@language": "en-US",
        "@value": "One"
      },
      "value": option_value,
      "next_screen": {
        "@id": "item/"+next_screen
      }
    },
    {
      "option_text": {
        "@language": "en-US",
        "@value": "None"
      },
      "value": 0
    }
  ];
}
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});
var metadata=screen.meta;
var data = new FormData();
data.append('metadata', JSON.stringify(metadata));
xhr.open("PUT", "http://" + window.host + "/api/v1/item/" + screen["_id"]);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(data);
meta = girder_connection.get(
    "item/{}".format(screens_ids[0])
)["meta"]
meta['options'] = [
    *[
        {
            **option,
            'next_screen': {
                "@id": "item/{}".format(
                    screens_ids[1]
                )
            }
        } for option in meta['options'] if option['value'] is not None
    ],
    *[
        option for option in meta['options'] if option['value'] is None
    ]
]

girder_connection.put(
    "?".join([
        "item/{}".format(screens_ids[0]),
        "metadata={}".format(
            quote(
                json.dumps(
                    meta
                )
            )
        )
    ])
)

delete screen

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    var screen_to_delete_id = JSON.parse(this.responseText)[0]["_id"];
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });
    xhr.open("DELETE", "http://" + window.host + "/api/v1/item/" + screen_to_delete_id);
    xhr.setRequestHeader("Girder-Token", window.authToken);
    xhr.send(null);
  }
});
xhr.open("GET", "http://" + window.host + "/api/v1/item?folderId=" + activity_version_id + "&name=" + name_of_screen_to_delete);
xhr.setRequestHeader("Girder-Token", window.authToken);
xhr.send(null);
girder_connection.delete(
    "item/{}".format(screen_id)
)
Clone this wiki locally