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.
Internal Python API
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, but you should use them like
normal objects. For example, to use the list method of the Group model:
from girder.models.group import Group
groups = 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
indexes they require. For example, to make a model whose documents live in a
collection called cat_collection and ensure that the name key is indexed
on that collection, you would use the following initialize method:
from girder.models.model_base import Model
class Cat(Model):
def initialize(self):
self.name = 'cat_collection'
self.ensureIndex('name')
Model Helper Functions
Model Base
API Key
User
Token
Group
Collection
Folder
Item
Setting
Assetstore
File
Upload
Web API Endpoints
Base Classes and Helpers
Utility
- class girder.utility.JsonEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
This extends the standard json.JSONEncoder to allow for more types to be sensibly serialized. This is used in Girder’s REST layer to serialize route return values when JSON is requested.
- default(obj)[source]
Implement this method in a subclass such that it returns a serializable object for
o, or calls the base implementation (to raise aTypeError).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- class girder.utility.RequestBodyStream(stream, size=None)[source]
Wraps a cherrypy request body into a more abstract file-like object.
- girder.utility.camelcase(value)[source]
Convert a module name or string with underscores and periods to camel case.
- Parameters:
value (str) – the string to convert
- Returns:
the value converted to camel case.
- girder.utility.genToken(length=64)[source]
Use this utility function to generate a random string of a desired length.
- girder.utility.mkdir(path, mode=511, recurse=True, existOk=True)[source]
Create a new directory or ensure a directory already exists.
- girder.utility.optionalArgumentDecorator(baseDecorator)[source]
This decorator can be applied to other decorators, allowing the target decorator to be used either with or without arguments.
The target decorator is expected to take at least 1 argument: the function to be wrapped. If additional arguments are provided by the final implementer of the target decorator, they will be passed to the target decorator as additional arguments.
For example, this may be used as:
@optionalArgumentDecorator def myDec(fun, someArg=None): ... @myDec def a(...): ... @myDec() def a(...): ... @myDec(5) def a(...): ... @myDec(someArg=5) def a(...): ...
- Parameters:
baseDecorator (callable) – The target decorator.
- girder.utility.parseTimestamp(x, naive=True)[source]
Parse a datetime string using the python-dateutil package.
If no timezone information is included, assume UTC. If timezone information is included, convert to UTC.
If naive is True (the default), drop the timezone information such that a naive datetime is returned.
- girder.utility.toBool(val)[source]
Coerce a string value to a bool. Meant to be used to parse HTTP parameters, which are always sent as strings. 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. This function is case-insensitive.
- Parameters:
val (str) – The value to coerce to a bool.
- 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 must have been registered using the
registerModel()method.plugin (str) – Plugin identifier (if this is a plugin model).
- Returns:
The instantiated model, which is a singleton.
- class girder.utility.setting_utilities.default(key)[source]
Create a decorator indicating that the wrapped function is responsible for providing the default value for the given key or set of keys.
- girder.utility.setting_utilities.getDefaultFunction(key)[source]
Retrieve the default value function for the given key. Returns
Noneif none is registered.
- girder.utility.setting_utilities.getValidator(key)[source]
Retrieve the validator function for the given key. Returns
Noneif none is registered.
- girder.utility.setting_utilities.registerDefaultFunction(key, fn)[source]
Register a default value function for a given setting key.
- Parameters:
key (str) – The setting key.
fn (callable) – The function that will return the default value for this key.
- girder.utility.setting_utilities.registerValidator(key, fn, replace=False)[source]
Register a validator for a given setting key.
- Parameters:
- class girder.utility.setting_utilities.validator(key, replace=False)[source]
Create a decorator indicating that the wrapped function is responsible for validating the given key or set of keys. For example,
>>> @validator('my_plugin.setting_key') >>> def validateMySetting(doc): >>> if not doc['value']: >>> raise ValidationException('This key must not be empty.')
- class girder.utility.webroot.WebrootBase(templatePath)[source]
Serves a template file in response to GET requests.
This will typically be the base class of any non-API endpoints.
- setTemplatePath(templatePath)[source]
Set the path to a template file to render instead of the default template.
The default template remains available so that custom templates can inherit from it. To do so, save the default template filename from the templateFilename attribute before calling this function, pass it as a variable to the custom template using updateHtmlVars(), and reference that variable in an <%inherit> directive like:
<%inherit file=”${context.get(‘defaultTemplateFilename’)}”/>
This module is essentially a subset of the python zipfile module that has been modified to allow it to read arbitrary streams (using generators) as input, instead of only accepting files. It also streams the output using generators.
Example of creating and consuming a streaming zip:
zip = ziputil.ZipGenerator(‘TopLevelFolder’)
- for data in zip.addFile(lambda: ‘hello world’, ‘hello.txt’):
yield data
yield zip.footer()
- class girder.utility.ziputil.ZipGenerator(rootPath='', compression=0)[source]
This class can be used to create a streaming zip file that consumes from one generator and writes to another.
- addFile(generator, path)[source]
Generates data to add a file at the given path in the archive. :param generator: Generator function that will yield the file contents. :type generator: function :param path: The path within the archive for this entry. :type path: str
Once all zip files have been added with addFile, you must call this to get the footer of the archive.
Constants
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 by calling:
girder.events.trigger('event.name', info)
- 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.
- 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.bound(eventName, handlerName, handler)[source]
A context manager to temporarily bind an event handler within its scope.
Parameters are the same as those to
girder.events.bind().
- girder.events.trigger(eventName, info=None, pre=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.
pre (function or None) – A function that will be executed prior to the handler being executed. It will receive a dict with a “handler” key, (the function), “info” key (the info arg to this function), and “eventName” and “handlerName” values.
Exceptions
Logging
Plugins
Python Client
Web client
Documentation for Girder’s web client library is not hosted online, but may be built locally by
running (from the top-level directory):
`bash
npm install && npm install --no-save esdoc esdoc-standard-plugin && npm run docs
`