API Documentation

RESTful API

Clients access Girder servers uniformly via its RESTful web API. By providing a single, stable, consistent web API, it is possible to write multiple interchangeable clients using different technologies.

When a Girder instance is deployed, it typically also serves a page that uses Swagger to document all available RESTful endpoints in the web API and also provide an easy way for users to execute those endpoints with parameters of their choosing. In this way, the Swagger page is just the simplest and lightest client application for Girder. This page is served out of the path /api under the root path of your Girder instance.

Models

In Girder, the model layer is responsible for actually interacting with the underlying database. Model classes are where the documents representing resources are actually saved, retrieved, and deleted from the DBMS. Validation of the resource documents is also done in the model layer, and is invoked each time a document is about to be saved.

Typically, there is a model class for each resource type in the system. These models are loaded as singletons for efficiency, and can be accessed in REST resources or other models by invoking self.model('foo'), where foo is the name of the model. For example:

groups = self.model('group').list(user=self.getCurrentUser())

All models that require the standard access control semantics should extend the AccessControlledModel class. Otherwise, they should extend the Model class.

All model classes must have an initialize method in which they declare the name of their corresponding Mongo collection, as well as any collection indices they require. For example:

from girder.models.model_base import Model

class Cat(Model):
    def initialize(self):
        self.name = 'cat_collection'

The above model singleton could then be accessed via:

self.model('cat')

If you wish to use models in something other than a REST Resource or Model, either mixin or instantiate the ModelImporter class.

Model Helper Functions

girder.models.getDbConfig()[source]

Get the database configuration values from the cherrypy config.

girder.models.getDbConnection()[source]

Get a MongoClient object that is connected to the configured database. We lazy-instantiate a module-level singleton, the MongoClient objects manage their own connection pools internally.

Model Base

class girder.models.model_base.AccessControlledModel[source]

Any model that has access control requirements should inherit from this class. It enforces permission checking in the load() method and provides convenient methods for testing and requiring user permissions. It also provides methods for setting access control policies on the resource.

copyAccessPolicies(src, dest, save=False)[source]

Copies the set of access control policies from one document to another.

Parameters:
  • src (dict) – The source document to copy policies from.
  • dest (dict) – The destination document to copy policies onto.
  • save (bool) – Whether to save the destination document after copying.
Returns:

The modified destination document.

filterResultsByPermission(cursor, user, level, limit, offset, removeKeys=())[source]

Given a database result cursor, this generator will yield only the results that the user has the given level of access on, respecting the limit and offset specified.

Parameters:
  • cursor – The database cursor object from “find()”.
  • user – The user to check policies against.
  • level (AccessType) – The access level.
  • limit – The max size of the result set.
  • offset – The offset into the result set.
  • removeKeys (list) – List of keys that should be removed from each matching document.
getAccessLevel(doc, user)[source]

Return the maximum access level for a given user on a given object. This can be useful for alerting the user which set of actions they are able to perform on the object in advance of trying to call them.

Parameters:
  • doc – The object to check access on.
  • user – The user to get the access level for.
Returns:

The max AccessType available for the user on the object.

getFullAccessList(doc)[source]

Return an object representing the full access list on this document. This simply includes the names of the users and groups with the access list.

hasAccess(doc, user=None, level=0)[source]

This method looks through the object’s permission set and determines whether the user has the given permission level on the object.

Parameters:
  • doc (dict) – The document to check permission on.
  • user (dict) – The user to check against.
  • level (AccessType) – The access level.
Returns:

Whether the access is granted.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

Override of Model.load to also do permission checking.

Parameters:
  • id (str or ObjectId) – The id of the resource.
  • user (dict or None) – The user to check access against.
  • level (AccessType) – The required access type for the object.
  • force (bool) – If you explicitly want to circumvent access checking on this resource, set this to True.
  • objectId (bool) – Whether the _id field is an ObjectId.
  • fields – The subset of fields to load from the returned document, or None to return the full document.
  • exc (bool) – If not found, throw a ValidationException instead of returning None.
Raises ValidationException:
 

If an invalid ObjectId is passed.

Returns:

The matching document, or None if no match exists.

requireAccess(doc, user=None, level=0)[source]

This wrapper just provides a standard way of throwing an access denied exception if the access check fails.

setAccessList(doc, access, save=False)[source]

Set the entire access control list to the given value. This also saves the resource in its new state to the database.

Parameters:
  • doc (dict) – The resource to update.
  • access (dict) – The new access control list to set on the object.
  • save (boolean) – Whether to save after updating.
Returns:

The updated resource.

setGroupAccess(doc, group, level, save=False)[source]

Set group-level access on the resource.

Parameters:
  • doc (dict) – The resource document to set access on.
  • group (dict) – The group to grant or remove access to.
  • level (AccessType or None) – What level of access the group should have. Set to None to remove all access for this group.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The updated resource document.

setPublic(doc, public, save=False)[source]

Set the flag for public read access on the object.

Parameters:
  • doc (dict) – The document to update permissions on.
  • public (bool) – Flag for public read access.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The updated resource document.

setUserAccess(doc, user, level, save=False)[source]

Set user-level access on the resource.

Parameters:
  • doc (dict) – The resource document to set access on.
  • user (dict) – The user to grant or remove access to.
  • level (AccessType or None) – What level of access the user should have. Set to None to remove all access for this user.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The modified resource document.

textSearch(query, user=None, filters=None, limit=50, offset=0, sort=None, fields=None)[source]

Custom override of Model.textSearch to also force permission-based filtering. The parameters are the same as Model.textSearch, except:

Parameters:user – The user to apply permission filtering for.
exception girder.models.model_base.AccessException[source]

Represents denial of access to a resource.

class girder.models.model_base.Model[source]

Model base class. Models are responsible for abstracting away the persistence layer. Each collection in the database should have its own model. Methods that deal with database interaction belong in the model layer.

ensureIndex(index)[source]

Like ensureIndices, but declares just a single index rather than a list of them.

ensureIndices(indices)[source]

Subclasses should call this with a list of strings representing fields that should be indexed in the database if there are any. Otherwise, it is not necessary to call this method. Elements of the list may also be a list or tuple, where the second element is a dictionary that will be passed as kwargs to the pymongo ensure_index call.

ensureTextIndex(index, language='english')[source]

Call this during initialize() of the subclass if you want your model to have a full-text searchable index. Each collection may have zero or one full-text index.

Parameters:language (str) – The default_language value for the text index, which is used for stemming and stop words. If the text index should not use stemming and stop words, set this param to ‘none’.
filterDocument(doc, allow=None)[source]

This method will filter the given document to make it suitable to output to the user.

Parameters:
  • doc (dict) – The document to filter.
  • allow (List of strings) – The whitelist of fields to allow in the output document.
find(query=None, offset=0, limit=50, **kwargs)[source]

Search the collection by a set of parameters. Passes any kwargs through to the underlying pymongo.collection.find function.

Parameters:
  • query (dict) – The search query (see general MongoDB docs for “find()”)
  • offset (int) – The offset into the results
  • limit (int) – Maximum number of documents to return
  • sort (List of (key, order) tuples.) – The sort order.
  • fields (List of strings) – A mask for filtering result documents by key.
Returns:

A pymongo database cursor.

findOne(query=None, **kwargs)[source]

Search the collection by a set of parameters. Passes any kwargs through to the underlying pymongo.collection.find function.

Parameters:
  • query (dict) – The search query (see general MongoDB docs for “find()”)
  • sort (List of (key, order) tuples.) – The sort order.
  • fields (List of strings) – A mask for filtering result documents by key.
Returns:

the first object that was found, or None if none found.

increment(query, field, amount, **kwargs)[source]

This is a specialization of the update method that atomically increments a field by a given amount. Additional kwargs are passed directly through to update.

Parameters:
  • query (dict) – The query selector for documents to update.
  • field (str) – The name of the field in the document to increment.
  • amount (int or float) – The amount to increment the field by.
initialize()[source]

Subclasses should override this and set the name of the collection as self.name. Also, they should set any indexed fields that they require.

load(id, objectId=True, fields=None, exc=False)[source]

Fetch a single object from the database using its _id field.

Parameters:
  • id (string or ObjectId) – The value for searching the _id field.
  • objectId (bool) – Whether the id should be coerced to ObjectId type.
  • fields – Fields list to include. Also can be a dict for exclusion. See pymongo docs for how to use this arg.
  • exc (bool) – Whether to raise a ValidationException if there is no document with the given id.
Returns:

The matching document, or None.

remove(document, **kwargs)[source]

Delete an object from the collection; must have its _id set.

Parameters:doc – the item to remove.
removeWithQuery(query)[source]

Remove all documents matching a given query from the collection. For safety reasons, you may not pass an empty query.

save(document, validate=True, triggerEvents=True)[source]

Create or update a document in the collection. This triggers two events; one prior to validation, and one prior to saving. Either of these events may have their default action prevented.

Parameters:
  • document (dict) – The document to save.
  • validate (bool) – Whether to call the model’s validate() before saving.
  • triggerEvents – Whether to trigger events for validate and pre- and post-save hooks.
subtreeCount(doc)[source]

Return the size of the subtree rooted at the given document. In general, if this contains items or folders, it will be the count of the items and folders in all containers. If it does not, it will be 1. This returns the absolute size of the subtree, it does not filter by permissions.

Parameters:doc (dict) – The root of the subtree.
textSearch(query, offset=0, limit=50, sort=None, fields=None, filters=None)[source]

Perform a full-text search against the text index for this collection.

Parameters:
  • query (str) – The text query. Will be stemmed internally.
  • filters (dict) – Any additional query operators to apply.
Returns:

A pymongo cursor. It is left to the caller to build the results from the cursor.

update(query, update, multi=True)[source]

This method should be used for updating multiple documents in the collection. This is useful for things like removing all references in this collection to a document that is being deleted from another collection.

This is a thin wrapper around pymongo db.collection.update().

For updating a single document, use the save() model method instead.

Parameters:
  • query (dict) – The query for finding documents to update. It’s the same format as would be passed to find().
  • update (dict) – The update specifier.
validate(doc)[source]

Models should implement this to validate the document before it enters the database. It must return the document with any necessary filters applied, or throw a ValidationException if validation of the document fails.

Parameters:doc (dict) – The document to validate before saving to the collection.
exception girder.models.model_base.ValidationException(message, field=None)[source]

Represents validation failure in the model layer. Raise this with a message and an optional field property. If one of these is thrown in the model during a REST request, it will respond as a 400 status.

Events

This module contains the Girder events framework. It maintains a global mapping of events to listeners, and contains utilities for callers to handle or trigger events identified by a name.

Listeners should bind to events by calling:

girder.events.bind('event.name', 'my.handler', handlerFunction)

And events should be fired in one of two ways; if the event should be handled synchronously, fire it with:

girder.events.trigger('event.name', info)

And if the event should be handled asynchronously, use:

girder.events.daemon.trigger('event.name', info, callback)

For obvious reasons, the asynchronous method does not return a value to the caller. Instead, the caller may optionally pass the callback argument as a function to be called when the task is finished. That callback function will receive the Event object as its only argument.

class girder.events.AsyncEventsThread[source]

This class is used to execute the pipeline for events asynchronously. This should not be invoked directly by callers; instead, they should use girder.events.daemon.trigger().

run()[source]

Loops over all queued events. If the queue is empty, this thread gets put to sleep until someone calls trigger() on it with a new event to dispatch.

stop()[source]

Gracefully stops this thread. Will finish the currently processing event before stopping.

trigger(eventName, info=None, callback=None)[source]

Adds a new event on the queue to trigger asynchronously.

Parameters:
  • eventName – The event name to pass to the girder.events.trigger
  • info – The info object to pass to girder.events.trigger
class girder.events.Event(name, info)[source]

An Event object is created when an event is triggered. It is passed to each of the listeners of the event, which have a chance to add information to the event, and also optionally stop the event from being further propagated to other listeners, and also optionally instruct the caller that it should not execute its default behavior.

addResponse(response)[source]

Listeners that wish to return data back to the caller who triggered this event should call this to append their own response to the event.

Parameters:response – The response value, which can be any type.
preventDefault()[source]

This can be used to instruct the triggerer of the event that the default behavior it would normally perform should not be performed. The semantics of this action are specific to the context of the event being handled, but a common use of this method is for a plugin to provide an alternate behavior that will replace the normal way the event is handled by the core system.

stopPropagation()[source]

Listeners should call this on the event they were passed in order to stop any other listeners to the event from being executed.

girder.events.bind(eventName, handlerName, handler)[source]

Bind a listener (handler) to the event identified by eventName. It is convention that plugins will use their own name as the handlerName, so that the trigger() caller can see which plugin(s) responded to the event.

Parameters:
  • eventName (str) – The name that identifies the event.
  • handlerName (str) – The name that identifies the handler calling bind().
  • handler (function) – The function that will be called when the event is fired. It must accept a single argument, which is the Event that was created by trigger(). This function should not return a value; any data that it needs to pass back to the triggerer should be passed via the addResponse() method of the Event.
girder.events.trigger(eventName, info=None)[source]

Fire an event with the given name. All listeners bound on that name will be called until they are exhausted or one of the handlers calls the stopPropagation() method on the event.

Parameters:
  • eventName (str) – The name that identifies the event.
  • info – The info argument to pass to the handler function. The type of this argument is opaque, and can be anything.
girder.events.unbind(eventName, handlerName)[source]

Removes the binding between the event and the given listener.

Parameters:
  • eventName (str) – The name that identifies the event.
  • handlerName (str) – The name that identifies the handler calling bind().
girder.events.unbindAll()[source]

Clears the entire event map. Any bound listeners will be unbound.

User

class girder.models.user.User[source]

This model represents the users of the system.

createUser(login, password, firstName, lastName, email, admin=False, public=True)[source]

Create a new user with the given information. The user will be created with the default “Public” and “Private” folders.

Parameters:
  • admin (bool) – Whether user is global administrator.
  • public (bool) – Whether user is publicly visible.
Returns:

The user document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this user’s folders.

Parameters:
  • doc – the user to list.
  • user – a user used to validate data that is returned.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the json string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath – if True, add the user’s name to the path.
remove(user, progress=None, **kwargs)[source]

Delete a user, and all references to it in the database.

Parameters:
  • user (dict) – The user document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
search(text=None, user=None, limit=50, offset=0, sort=None)[source]

List all users. Since users are access-controlled, this will filter them by access policy.

Parameters:
  • text – Pass this to perform a full-text search for users.
  • user – The user running the query. Only returns users that this user can see.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
Returns:

List of users.

setPassword(user, password, save=True)[source]

Change a user’s password.

Parameters:
  • user – The user whose password to change.
  • password – The new password. If set to None, no password will be stored for this user. This should be done in cases where an external system is responsible for authenticating the user.
subtreeCount(doc)[source]

Return the size of the user’s folders. The user is counted as well.

Parameters:doc – The user.
validate(doc)[source]

Validate the user every time it is stored in the database.

Password

class girder.models.password.Password[source]

This model deals with managing user passwords.

authenticate(user, password)[source]

Authenticate a user.

Parameters:
  • user (dict) – The user document.
  • password (str) – The attempted password.
Returns:

Whether authentication succeeded (bool).

encryptAndStore(password)[source]

Encrypt and store the given password. The exact internal details and mechanisms used for storage are abstracted away, but the guarantee is made that once this method is called on a password and the returned salt and algorithm are stored with the user document, calling Password.authenticate() with that user document and the same password will return True.

Parameters:password (str) – The password to encrypt and store.
Returns:{tuple} (salt, hashAlg) The salt to store with the user document and the algorithm used for secure storage. Both should be stored in the corresponding user document as ‘salt’ and ‘hashAlg’ respectively.

Token

class girder.models.token.Token[source]

This model stores session tokens for user authentication.

addScope(token, scope)[source]

Add a scope to this token. If the token already has the scope, this is a no-op.

createToken(user=None, days=180, scope=None)[source]

Creates a new token. You can create an anonymous token (such as for CSRF mitigation) by passing “None” for the user argument.

Parameters:
  • user (dict) – The user to create the session for.
  • days (int) – The lifespan of the session in days.
  • scope (str or list of str) – Scope or list of scopes this token applies to. By default, will create a user authentication token.
Returns:

The token document that was created.

getAllowedScopes(token)[source]

Return the list of allowed scopes for a given token.

hasScope(token, scope)[source]

Test whether the given token has the given set of scopes. Use this rather than comparing manually, since this method is backward compatible with tokens that do not contain a scope field.

Parameters:
  • token (dict) – The token object.
  • scope – A scope or set of scopes that will be tested as a subset of the given token’s allowed scopes.
girder.models.token.genToken(length=64)[source]

Use this utility function to generate a random string of a desired length.

Group

class girder.models.group.Group[source]

Groups are simply groups of users. The primary use of grouping users is to simplify access control for resources in the system, but they can be used for other purposes that require groupings of users as well.

Group membership is stored in the database on the user document only; there is no “users” field in this model. This is to optimize for the most common use case for querying membership, which involves checking access control policies, which is always done relative to a specific user. The task of querying all members within a group is much less common and typically only performed on a single group at a time, so doing a find on the indexed group list in the user collection is sufficiently fast.

Users with READ access on the group can see the group and its members. Users with WRITE access on the group can add and remove members and change the name or description. Users with ADMIN access can promote group members to grant them WRITE or ADMIN access, and can also delete the entire group.

This model uses a custom implementation of the access control methods, because it uses only a subset of its capabilities and provides a more optimized implementation for that subset. Specifically: read access is implied by membership in the group or having an invitation to join the group, so we don’t store read access in the access document as normal. Another constraint is that write and admin access on the group can only be granted to members of the group. Also, group permissions are not allowed on groups for the sake of simplicity.

addUser(group, user, level=0)[source]

Add the user to the group. Records membership in the group in the user document, and also grants the specified access level on the group itself to the user. Any group member has at least read access on the group. If the user already belongs to the group, this method can be used to change their access level within it.

createGroup(name, creator, description='', public=True)[source]

Create a new group. The creator will be given admin access to it.

Parameters:
  • name (str) – The name of the folder.
  • description (str) – Description for the folder.
  • public (bool) – Whether the group is publicly visible.
  • creator (dict) – User document representing the creator of the group.
Returns:

The group document that was created.

filter(group, user, accessList=False, requests=False)[source]

Filter a group document for display to the user.

Parameters:
  • group (dict) – The document to filter.
  • user (dict) – The current user.
  • accessList (bool) – Whether to include the access control list field.
  • requests (bool) – Whether to include the requests list field.
Returns:

The filtered group document.

getAccessLevel(doc, user)[source]

Return the maximum access level for a given user on the group.

Parameters:
  • doc – The group to check access on.
  • user – The user to get the access level for.
Returns:

The max AccessType available for the user on the object.

getFullRequestList(group)[source]

Return the set of all outstanding requests, filled in with the login and full names of the corresponding users.

Parameters:group (dict) – The group to get requests for.
getInvites(group, limit=50, offset=0, sort=None)[source]

Return a page of outstanding invitations to a group. This is simply a list of users invited to the group currently.

Parameters:
  • group – The group to find invitations for.
  • limit – Result set size limit.
  • offset – Offset into the results.
  • sort – The sort field.
getMembers(group, offset=0, limit=50, sort=None)[source]

Return the list of all users who belong to this group.

Parameters:
  • group – The group to list members on.
  • offset – Offset into the result set of users.
  • limit – Result set size limit.
  • sort – Sort parameter for the find query.
Returns:

List of user documents.

hasAccess(doc, user=None, level=0)[source]

This overrides the default AccessControlledModel behavior for checking access to perform an optimized subset of the access control behavior.

Parameters:
  • doc (dict) – The group to check permission on.
  • user (dict) – The user to check against.
  • level (AccessType) – The access level.
Returns:

Whether the access is granted.

inviteUser(group, user, level=0)[source]

Invite a user to join the group. Inviting them automatically grants the user read access to the group so that they can see it. Once they accept the invitation, they will be given the specified level of access.

If the user has requested an invitation to this group, calling this will accept their request and add them to the group at the access level specified.

joinGroup(group, user)[source]

This method either accepts an invitation to join a group, or if the given user has not been invited to the group, this will create an invitation request that moderators and admins may grant or deny later.

list(user=None, limit=50, offset=0, sort=None)[source]

Search for groups or simply list all visible groups.

Parameters:
  • text – Pass this to perform a text search of all groups.
  • user – The user to search as.
  • limit – Result set size limit.
  • offset – Offset into the results.
  • sort – The sort direction.
listMembers(group, offset=0, limit=50, sort=None)[source]

List members of the group, with names, ids, and logins.

remove(group, **kwargs)[source]

Delete a group, and all references to it in the database.

Parameters:group (dict) – The group document to delete.
removeUser(group, user)[source]

Remove the user from the group. If the user is not in the group but has an outstanding invitation to the group, the invitation will be revoked. If the user has requested an invitation, calling this will deny that request, thereby deleting it.

setUserAccess(doc, user, level, save=False)[source]

This override is used because we only need to augment the access field in the case of WRITE access and above since READ access is implied by membership or invitation.

updateGroup(group)[source]

Updates a group.

Parameters:group (dict) – The group document to update
Returns:The group document that was edited.

Collection

class girder.models.collection.Collection[source]

Collections are the top level roots of the data hierarchy. They are used to group and organize data that is meant to be shared amongst users.

createCollection(name, creator, description='', public=True)[source]

Create a new collection.

Parameters:
  • name (str) – The name of the collection. Must be unique.
  • description (str) – Description for the collection.
  • public (bool) – Public read access flag.
  • creator (dict) – The user who is creating this collection.
Returns:

The collection document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this collection’s folders.

Parameters:
  • doc – the collection to list.
  • user – a user used to validate data that is returned.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the json string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath – if True, add the collection’s name to the path.
filter(collection, user=None)[source]

Helper to filter the collection model.

list(user=None, limit=50, offset=0, sort=None)[source]

Search for collections with full text search.

remove(collection, progress=None, **kwargs)[source]

Delete a collection recursively.

Parameters:
  • collection (dict) – The collection document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
subtreeCount(doc)[source]

Return the size of the folders within the collection. The collection is counted as well.

Parameters:doc – The collection.
updateCollection(collection)[source]

Updates a collection.

Parameters:collection (dict) – The collection document to update
Returns:The collection document that was edited.

Folder

class girder.models.folder.Folder[source]

Folders are used to store items and can also store other folders in a hierarchical way, like a directory on a filesystem. Every folder has its own set of access control policies, but by default the access control list is inherited from the folder’s parent folder, if it has one. Top-level folders are ones whose parent is a user or a collection.

childFolders(parent, parentType, user=None, limit=50, offset=0, sort=None, filters=None, **kwargs)[source]

This generator will yield child folders of a user, collection, or folder, with access policy filtering. Passes any kwargs to the find function.

Parameters:
  • parent – The parent object.
  • parentType (‘user’, ‘folder’, or ‘collection’) – The parent type.
  • user – The user running the query. Only returns folders that this user can see.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
  • filters – Additional query operators.
childItems(folder, limit=50, offset=0, sort=None, filters=None, **kwargs)[source]

Generator function that yields child items in a folder. Passes any kwargs to the find function.

Parameters:
  • folder – The parent folder.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
  • filters – Additional query operators.
copyFolder(srcFolder, parent=None, name=None, description=None, parentType=None, public=None, creator=None, progress=None)[source]

Copy a folder, including all child items and child folders.

Parameters:
  • srcFolder (dict) – the folder to copy.
  • parent (dict) – The parent document. Must be a folder, user, or collection.
  • name (str) – The name of the new folder. None to copy the original name.
  • description (str) – Description for the new folder. None to copy the original description.
  • parentType (str) – What type the parent is: (‘folder’ | ‘user’ | ‘collection’)
  • public (bool, None, or ‘original’.) – Public read access flag. None to inherit from parent, ‘original’ to inherit from original folder.
  • creator (dict) – user representing the creator of the new folder.
  • progress (girder.utility.progress.ProgressContext or None.) – a progress context to record process on.
Returns:

the new folder document.

copyFolderComponents(srcFolder, newFolder, creator, progress)[source]

Copy the items, subfolders, and extended data of a folder that was just copied.

Parameters:
  • srcFolder (dict) – the original folder.
  • newFolder – the new folder.
  • creator (dict) – user representing the creator of the new folder.
  • progress (girder.utility.progress.ProgressContext or None.) – a progress context to record process on.
Returns:

the new folder document.

createFolder(parent, name, description='', parentType='folder', public=None, creator=None, allowRename=False)[source]

Create a new folder under the given parent.

Parameters:
  • parent (dict) – The parent document. Should be a folder, user, or collection.
  • name (str) – The name of the folder.
  • description (str) – Description for the folder.
  • parentType (str) – What type the parent is: (‘folder’ | ‘user’ | ‘collection’)
  • public (bool or None to inherit from parent) – Public read access flag.
  • creator (dict) – User document representing the creator of this folder.
  • allowRename – if True and a folder or item of this name exists, automatically rename the folder.
Returns:

The folder document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this folder.

Parameters:
  • doc – the folder to list.
  • user – the user used for access.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the json string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the folder.
  • subpath – if True, add the folder’s name to the path.
filter(folder, user)[source]

Filter a folder document for display to the user.

getSizeRecursive(folder)[source]

Calculate the total size of the folder by recursing into all of its descendent folders.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

We override load in order to ensure the folder has certain fields within it, and if not, we add them lazily at read time.

Parameters:
  • id (string or ObjectId) – The id of the resource.
  • user (dict or None) – The user to check access against.
  • level (AccessType) – The required access type for the object.
  • force (bool) – If you explicitly want to circumvent access checking on this resource, set this to True.
move(folder, parent, parentType)[source]

Move the given folder from its current parent to another parent object. Raises an exception if folder is an ancestor of parent.

Parameters:
  • folder (dict) – The folder to move.
  • parent – The new parent object.
  • parentType (str) – The type of the new parent object (user, collection, or folder).
parentsToRoot(folder, curPath=None, user=None, force=False, level=0)[source]

Get the path to traverse to a root of the hierarchy.

Parameters:folder (dict) – The folder whose root to find
Returns:an ordered list of dictionaries from root to the current folder
remove(folder, progress=None, **kwargs)[source]

Delete a folder recursively.

Parameters:
  • folder (dict) – The folder document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
setMetadata(folder, metadata)[source]

Set metadata on a folder. A rest exception is thrown in the cases where the metadata json object is badly formed, or if any of the metadata keys contains a period (‘.’).

Parameters:
  • folder (dict) – The folder to set the metadata on.
  • metadata (dict) – A dictionary containing key-value pairs to add to the folder’s meta field
Returns:

the folder document

subtreeCount(folder)[source]

Return the size of the subtree rooted at the given folder. Includes the root folder in the count. Counts folders and items. This returns the absolute size of the subtree, it does not filter by permissions.

Parameters:folder (dict) – The root of the subtree.
updateFolder(folder)[source]

Updates a folder.

Parameters:folder (dict) – The folder document to update
Returns:The folder document that was edited.
validate(doc, allowRename=False)[source]

Validate the name and description of the folder, ensure that it is associated with a valid parent and that it has a unique name.

Parameters:
  • doc – the folder document to validate.
  • allowRename – if True and a folder or item exists with the same name, rename the folder so that it is unique.
Return doc:

the validated folder document.

Item

class girder.models.item.Item[source]

Items are leaves in the data hierarchy. They can contain 0 or more files within them, and can also contain arbitrary metadata.

childFiles(item, limit=50, offset=0, sort=None, **kwargs)[source]

Generator function that yields child files in the item. Passes any kwargs to the find function.

Parameters:
  • item – The parent item.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
copyItem(srcItem, creator, name=None, folder=None, description=None)[source]

Copy an item, including duplicating files and metadata.

Parameters:
  • srcItem (dict) – the item to copy.
  • creator – the user who will own the copied item.
  • name (str) – The name of the new item. None to copy the original name.
  • folder – The parent folder of the new item. None to store in the same folder as the original item.
  • description (str) – Description for the new item. None to copy the original description.
Returns:

the new item.

createItem(name, creator, folder, description='')[source]

Create a new item. The creator will be given admin access to it.

Parameters:
  • name (str) – The name of the item.
  • description (str) – Description for the item.
  • folder – The parent folder of the item.
  • creator (dict) – User document representing the creator of the group.
Returns:

The item document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this item.

Parameters:
  • doc – the item to list.
  • user – a user used to validate data that is returned. This isn’t used, but is present to be consistent across all model implementations of fileList.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the json string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath – if True and the item has more than one file, metadata, or the sole file is not named the same as the item, then the returned paths include the item name.
filter(item)[source]

Filter an item document for display to the user.

filterResultsByPermission(cursor, user, level, limit, offset, removeKeys=())[source]

This method is provided as a convenience for filtering a result cursor of items by permissions, based on the parent folder. The results in the cursor must contain the folderId field.

hasAccess(item, user=None, level=0)[source]

Test access for a given user to this item. Simply calls this method on the parent folder.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

We override Model.load to also do permission checking.

Parameters:
  • id (string or ObjectId) – The id of the resource.
  • user (dict or None) – The user to check access against.
  • level (AccessType) – The required access type for the object.
  • force (bool) – If you explicity want to circumvent access checking on this resource, set this to True.
move(item, folder)[source]

Move the given item from its current folder into another folder.

Parameters:
  • item (dict) – The item to move.
  • folder (dict.) – The folder to move the item into.
parentsToRoot(item, user=None, force=False)[source]

Get the path to traverse to a root of the hierarchy.

Parameters:item (dict) – The item whose root to find
Returns:an ordered list of dictionaries from root to the current item
remove(item, **kwargs)[source]

Delete an item, and all references to it in the database.

Parameters:item (dict) – The item document to delete.
setMetadata(item, metadata)[source]

Set metadata on an item. A rest exception is thrown in the cases where the metadata json object is badly formed, or if any of the metadata keys contains a period (‘.’).

Parameters:
  • item (dict) – The item to set the metadata on.
  • metadata (dict) – A dictionary containing key-value pairs to add to the items meta field
Returns:

the item document

textSearch(query, user=None, filters=None, limit=50, offset=0, sort=None, fields=None)[source]

Custom override of Model.textSearch to filter items by permissions of the parent folder.

updateItem(item)[source]

Updates an item.

Parameters:item (dict) – The item document to update
Returns:The item document that was edited.

Setting

class girder.models.setting.Setting[source]

This model represents server-wide configuration settings as key/value pairs.

get(key, default='__default__')[source]

Retrieve a setting by its key.

Parameters:
  • key (str) – The key identifying the setting.
  • default – If no such setting exists, returns this value instead.
Returns:

The value, or the default value if the key is not found.

getDefault(key)[source]

Retreive the system default for a value.

Parameters:key (str) – The key identifying the setting.
Returns:The default value if the key is present in both SettingKey and referenced in SettingDefault; otherwise None.
set(key, value)[source]

Save a setting. If a setting for this key already exists, this will replace the existing value.

Parameters:
  • key (str) – The key identifying the setting.
  • value – The object to store for this setting.
Returns:

The document representing the saved Setting.

unset(key)[source]

Remove the setting for this key. If no such setting exists, this is a no-op.

Parameters:key (str) – The key identifying the setting to be removed.
validate(doc)[source]

This method is in charge of validating that the setting key is a valid key, and that for that key, the provided value is valid. It first allows plugins to validate the setting, but if none of them can, it assumes it is a core setting and does the validation here.

validateCorePluginsEnabled(doc)[source]

Ensures that the set of plugins passed in is a list of valid plugin names. Removes any invalid plugin names, removes duplicates, and adds all transitive dependencies to the enabled list.

Python API for RESTful web API

Base Classes and Helpers

class girder.api.rest.Resource[source]

All REST resources should inherit from this class, which provides utilities for adding resources/routes to the REST API.

boolParam(key, params, default=None)[source]

Coerce a parameter value from a str to a bool. This function is case insensitive. The following string values will be interpreted as True:

  • 'true'
  • 'on'
  • '1'
  • 'yes'

All other strings will be interpreted as False. If the given param is not passed at all, returns the value specified by the default arg.

deleteAuthTokenCookie()[source]

Helper method to kill the authentication cookie

ensureTokenScopes(scope)[source]

Ensure that the token passed to this request is authorized for the designated scope or set of scopes. Raises an AccessException if not.

Parameters:scope (str or list of str) – A scope or set of scopes that is required.
getCurrentToken()[source]

Returns the current valid token object that was passed via the token header or parameter, or None if no valid token was passed.

getCurrentUser(returnToken=False)[source]

Returns the currently authenticated user based on the token header or parameter.

Parameters:returnToken (bool) – Whether we should return a tuple that also contains the token.
Returns:The user document from the database, or None if the user is not logged in or the token is invalid or expired. If returnToken=True, returns a tuple of (user, token).
getPagingParameters(params, defaultSortField=None, defaultSortDir=1)[source]

Pass the URL parameters into this function if the request is for a list of resources that should be paginated. It will return a tuple of the form (limit, offset, sort) whose values should be passed directly into the model methods that are finding the resources. If the client did not pass the parameters, this always uses the same defaults of limit=50, offset=0, sort=’name’, sortdir=pymongo.ASCENDING=1.

Parameters:
  • params (dict) – The URL query parameters.
  • defaultSortField (str or None) – If the client did not pass a ‘sort’ parameter, set this to choose a default sort field. If None, the results will be returned unsorted.
handleRoute(method, path, params)[source]

Match the requested path to its corresponding route, and calls the handler for that route with the appropriate kwargs. If no route matches the path requested, throws a RestException.

This method fires two events for each request if a matching route is found. The names of these events are derived from the route matched by the request. As an example, if the user calls GET /api/v1/item/123, the following two events would be fired:

rest.get.item/:id.before

would be fired prior to calling the default API function, and

rest.get.item/:id.after

would be fired after the route handler returns. The query params are passed in the info of the before and after event handlers as event.info[‘params’], and the matched route tokens are passed in as dict items of event.info, so in the previous example event.info would also contain an ‘id’ key with the value of 123. For endpoints with empty sub-routes, the trailing slash is omitted from the event name, e.g.:

rest.post.group.before

Note: You will normally not need to call this method directly, as it is called by the internals of this class during the routing process.

Parameters:
  • method (str) – The HTTP method of the current request.
  • path (list) – The path params of the request.
removeRoute(method, route, handler=None, resource=None)[source]

Remove a route from the handler and documentation.

Parameters:
  • method (str) – The HTTP method, e.g. ‘GET’, ‘POST’, ‘PUT’
  • route (list) – The route, as a list of path params relative to the resource root. Elements of this list starting with ‘:’ are assumed to be wildcards.
  • handler (function) – The method called for the route; this is necessary to remove the documentation.
  • resource – the name of the resource at the root of this route.
requireAdmin(user)[source]

Calling this on a user will ensure that they have admin rights. If not, raises an AccessException.

Parameters:user (dict.) – The user to check admin flag on.
Raises AccessException:
 If the user is not an administrator.
requireParams(required, provided)[source]

Throws an exception if any of the parameters in the required iterable is not found in the provided parameter set.

Parameters:
  • required (list, tuple, or str) – An iterable of required params, or if just one is required, you can simply pass it as a string.
  • provided (dict) – The list of provided parameters.
route(method, route, handler, nodoc=False, resource=None)[source]

Define a route for your REST resource.

Parameters:
  • method (str) – The HTTP method, e.g. ‘GET’, ‘POST’, ‘PUT’, ‘PATCH’
  • route (list) – The route, as a list of path params relative to the resource root. Elements of this list starting with ‘:’ are assumed to be wildcards.
  • handler (function) – The method to be called if the route and method are matched by a request. Wildcards in the route will be expanded and passed as kwargs with the same name as the wildcard identifier.
  • nodoc (bool) – If your route intentionally provides no documentation, set this to True to disable the warning on startup.
  • resource – The name of the resource at the root of this route.
sendAuthTokenCookie(user)[source]

Helper method to send the authentication cookie

exception girder.api.rest.RestException(message, code=400, extra=None)[source]

Throw a RestException in the case of any sort of incorrect request (i.e. user/client error). Login and permission failures should set a 403 code; almost all other validation errors should use status 400, which is the default.

girder.api.rest.endpoint(fun)[source]

REST HTTP method endpoints should use this decorator. It converts the return value of the underlying method to the appropriate output format and sets the relevant response headers. It also handles RestExceptions, which are 400-level exceptions in the REST endpoints, AccessExceptions resulting from access denial, and also handles any unexpected errors using 500 status and including a useful traceback in those cases.

If you want a streamed response, simply return a generator function from the inner method.

girder.api.rest.ensureTokenScopes(token, scope)[source]

Call this to validate a token scope for endpoints that require tokens other than a user authentication token. Raises an AccessException if the required scopes are not allowed by the given token.

Parameters:
  • token (dict) – The token object used in the request.
  • scope (str or list of str) – The required scope or set of scopes.
class girder.api.rest.loadmodel(map, model, plugin='_core', level=None, force=False)[source]

This is a decorator that can be used to load a model based on an ID param. For access controlled models, it will check authorization for the current user. The underlying function is called with a modified set of keyword arguments that is transformed by the “map” parameter of this decorator.

Parameters:
  • map (dict) – Map of incoming parameter name to corresponding model arg name.
  • model (str) – The model name, e.g. ‘folder’
  • plugin (str) – Plugin name, if loading a plugin model.
  • level (AccessType) – Access level, if this is an access controlled model.
girder.api.rest.requireAdmin(user)[source]

Calling this on a user will ensure that they have admin rights. If not, raises an AccessException.

Parameters:user (dict.) – The user to check admin flag on.
Raises AccessException:
 If the user is not an administrator.

User

Group

Item

Folder

Utility

class girder.utility.model_importer.ModelImporter[source]

Any class that wants to have convenient model importing semantics should extend/mixin this class.

static model(model, plugin='_core')[source]

Call this to get the instance of the specified model. It will be lazy-instantiated.

Parameters:
  • model (string) – The name of the model to get. This is the module name, e.g. “folder”. The class name must be the upper-camelcased version of that module name, e.g. “Folder”.
  • plugin – If the model you wish to load is a model within a plugin, set this to the name of the plugin containing the model.
Returns:

The instantiated model, which is a singleton.

girder.utility.model_importer.clearModels()[source]

Force reloading of all models by clearing the singleton cache. This is used by the test suite to ensure that indices are built properly at startup.

girder.utility.server.configureServer(test=False, plugins=None, curConfig=None)[source]

Function to setup the cherrypy server. It configures it, but does not actually start it.

Parameters:
  • test (bool) – Set to True when running in the tests.
  • plugins – If you wish to start the server with a custom set of plugins, pass this as a list of plugins to load. Otherwise, will use the PLUGINS_ENABLED setting value from the db.
  • curConfig – The configuration dictionary to update.
girder.utility.server.setup(test=False, plugins=None, curConfig=None)[source]

Configure and mount the Girder server under ‘/’.

Parameters:
  • test – Whether to start in test mode.
  • plugins – List of plugins to enable.
  • curConfig – The config object to update.
girder.utility.mail_utils.addTemplateDirectory(dir)[source]

Adds a directory to the search path for mail templates. This is useful for plugins that have their own set of mail templates.

Parameters:dir (str) – The directory to add to the template lookup path.
girder.utility.mail_utils.renderTemplate(name, params=None)[source]

Renders one of the HTML mail templates located in girder/mail_templates.

Parameters:
  • name – The name of the file inside girder/mail_templates to render.
  • params (dict) – The parameters to pass when rendering the template.
Returns:

The rendered template as a string of HTML.

girder.utility.mail_utils.sendEmail(to, subject, text)[source]

Send an email. This builds the appropriate email object and then triggers an asynchronous event to send the email (handled in _sendmail).

Parameters:
  • to (str) – The recipient’s email address.
  • subject (str) – The subject line of the email.
  • text (str) – The body of the email.

Constants

Constants should be defined here.

class girder.constants.AccessType[source]

Represents the level of access granted to a user or group on an AccessControlledModel. Having a higher access level on a resource also confers all of the privileges of the lower levels.

Semantically, READ access on a resource means that the user can see all the information pertaining to the resource, but cannot modify it.

WRITE access usually means the user can modify aspects of the resource.

ADMIN access confers total control; the user can delete the resource and also manage permissions for other users on it.

class girder.constants.AssetstoreType[source]

All possible assetstore implementation types.

class girder.constants.SettingDefault[source]

Core settings that have a default should be enumerated here with the SettingKey.

class girder.constants.SettingKey[source]

Core settings should be enumerated here by a set of constants corresponding to sensible strings.

class girder.constants.TerminalColor[source]

Provides a set of values that can be used to color text in the terminal.

class girder.constants.TokenScope[source]

Constants for core token scope strings. Token scopes must not contain spaces, since many services accept scope lists as a space-separated list of strings.

Clients

jQuery Plugins

There are a set of jQuery plugins that interact with the Girder API. These can be found in the clients/jquery directory of the source tree.

$.girderBrowser(cfg)
Arguments:
  • cfg (object) – Configuration object
  • caret (boolean) – Draw a caret on main menu to indicate dropdown (true by default).
  • label (string) – The text to display in the main menu dropdown.
  • api (string) – The root path to the Girder API (/api/v1 by default).
  • selectItem (function(item,api)) – A function to call when an item is clicked. It will be passed the item’s information and the API root.
  • selectFolder (function(folder,api)) – A function to call when a folder is clicked. It will be passed the folder’s information and the API root.
  • search (boolean) – Include a search box for gathering general string search results.
  • selectSearchResult (function(result,api)) – A function to call when a search result is clicked. It will be passed the result item’s information and the API root.

This plugin creates a Bootsrap dropdown menu reflecting the current contents of a Girder server as accessible by the logged-in user. The selection on which this plugin is invoked should be an <li> element that is part of a Bootstrap navbar. For example:

<div class="navbar navbar-default navbar-fixed-top">
    <div class=navbar-header>
        <a class=navbar-brand href=/examples>Girder</a>
    </div>

    <ul class="nav navbar-nav">
        <li id=girder-browser>
            <a>Dummy</a>
        </li>
    </ul>
</div>

Then, in a JavaScript file:

$("#girder-browser").girderBrowser({
    // Config options here
    //     .
    //     .
    //     .
});

The anchor text “dummy” in the example HTML will appear in the rendered page if the plugin fails to execute for any reason. This is purely a debugging measure - since the plugin empties the target element before it creates the menu, the anchor tag (or any other content) is not required.