Gallery3:API:REST - Gallery Codex
Personal tools

Gallery3:API:REST

From Gallery Codex

Introduction

Gallery 3 comes with an API that lets you interact with the application without using the website. This is very useful for creating scripts or embedding Gallery 3 into other applications seamlessly. The API uses the Representational State Transfer (REST) model which uses HTTP requests as the basic way to have your remote client script talk to the Gallery 3 server. The interface is consistent and easy to use.

In our RESTful API, we refer to everything as either an entity or a collection. Albums and tags are collections. Photos, movies and comments are entities. Collections contain entities, but in some cases collections can also be entities. For example an album is both a collection, and an entity in and of itself. Every resource has its own individual URL which can be used to refer to it. If you want to get information about a resource you perform an HTTP GET request on the resource URL. You can modify the contents of a collection or the attributes of an entity using HTTP POST, PUT and DELETE requests.

This documentation explains how to use the Gallery 3 REST API to provide remote access to a Gallery 3 installation from web and native clients using the HTTP protocol. It also explains how to add your own RESTful interfaces using the provided REST framework.

Enabling REST access

REST support in Gallery 3 is provided by the rest module, which is distributed with the latest Gallery 3 code. Because it provides a powerful interface to your Gallery that you may not wish to make available, it is not enabled by default. To enable it, you must activate the rest module in Admin » Modules.

Request Format

REST uses the GET, POST, PUT and DELETE verbs as part of the HTTP protocol. However since many Apache servers don't support the HTTP PUT and DELETE actions in the default configuration, we rely on HTTP POST and pass the real verb in the X-Gallery-Request-Method header.

You can request details about any resource using the GET verb. To create a new resource, use the POST verb. To update an existing resource, use the PUT verb. To remove a resource, use the DELETE verb. When creating or updating a resource, specify key value pairs in the HTTP content. Gallery will take whatever action that it legally can with the data that you provide. All user level security restrictions are in effect -- you cannot do anything via the REST interface that your user can't do from the web interface. If your request contains bad data, the an "HTTP 400 Bad Request" response will be returned. When creating a new entity that requires an associated data file, use a HTTP Multipart/MIME request.

Example view request

 GET /gallery3/index.php/rest/item/1 HTTP/1.1
 Host: example.com
 X-Gallery-Request-Method: get
 X-Gallery-Request-Key: ...
 Content-Length: 0

Example create request

 POST /gallery3/index.php/rest/item/1 HTTP/1.1
 Host: example.com
 X-Gallery-Request-Method: post
 X-Gallery-Request-Key: ...
 Content-Type: application/x-www-form-urlencoded
 Content-Length: 117
 entity=%7B%22type%22%3A%22album%22%2C%22name%22%3A%22Sample+Album%22%2C%22title%22%3A%22  
 This+is+my+Sample+Album%22%7D

Note the original value is JSON encoded for Gallery 3, and then URL encoded for HTTP. The above value decodes into:

 entity {
   type: "album"
   name: "Sample Album"
   title: "This is my Sample Album"
 }

We provide a PHP client library that does this encoding for you. But if you're not using a client library, you could build the above value in raw PHP with:

 <?php
 $data = array("type" => "album", ...);
 print "entity=" . urlencode(json_encode($data));
 ?>

Example update request

 POST /gallery3/index.php/rest/item/48 HTTP/1.1
 Host: example.com
 X-Gallery-Request-Method: put
 X-Gallery-Request-Key: ...
 Content-Type: application/x-www-form-urlencoded
 Content-Length: 69
 entity=%7B%22title%22%3A%22This+is+the+new+title%22%7D&members=%5B%5D

More examples

More examples are documented on a separate page, because they can get quite verbose. Additional implementation(s) available in: python, java-android and perl.

Response Format

By default, data returned from the server is JSON encoded. You can request that the data returned is in HTML format by adding "output=html" as a query parameter on your request. The output query parameter is sticky; all RESTful urls will also have this as well. This is convenient if you want to navigate around your Gallery via the RESTful interface in a web browser.

Each response contains an associative array containing the following top level keys:

  • url
    • The url of the resource that you've requested. You just used this value to request this response, so it's redundant to have it here, but it provides a nice identifier for the response data.
  • entity
    • Key/value pairs containing information about the entity itself.
  • members
    • If the resource is a collection, the members array will contain an array of REST resources, each of which is a member of the collection. Note that the contents of the members array can be modified based on query parameters passed in as part of the request.
  • relationships
    • Gallery is modular, which means that it contains a variety of loosely connected data sets. Here, modules can provide collections of related resources. For example, the tags collection can provided a collection of tags related to the current item. This allows you to easily navigate around data sets.

Example view response

 GET /gallery3/index.php/rest/item/1
 ...
 HTTP/1.1 200 OK
 Content-Length: 1200
 Content-Type: application/json
 {"url":"http:\/\/example.com\/gallery3\/index.php\/rest\/item\/1","entity":{"id":"1","captured":
 null,"created":"1270793819","description":"","height":null,"level":"1","mime_type":null,
 "name":null,"owner_id":"2","rand_key":null,"resize_height":null,"resize_width":null,"slug":null,
 "sort_column":"weight","sort_order":"ASC","thumb_height":"103","thumb_width":"164","title":
 "Gallery","type":"album","updated":"1270958456","view_count":"0","width":null,"view_1":"1",
 "view_2":"1","album_cover":"http:\/\/example.com\/gallery3\/index.php\/rest\/item\/3",
 "thumb_url":"http:\/\/example.com\/gallery3\/var\/thumbs\/\/.album.jpg?m=1270958456"},
 "relationships":{"tags":{"url":"http:\/\/example.com\/gallery3\/index.php\/rest\/item_tags\/1",
 "members":["http:\/\/example.com\/gallery3\/index.php\/rest\/tag_item\/9,1",
 "http:\/\/example.com\/gallery3\/index.php\/rest\/tag_item\/10,1"]}},"members":[
 "http:\/\/example.com\/gallery3\/index.php\/rest\/item\/7",
 "http:\/\/example.com\/gallery3\/index.php\/rest\/item\/11",
 "http:\/\/example.com\/gallery3\/index.php\/rest\/item\/26"]}

After running the response through json_decode, you'll have a PHP array containing the following data:

 {
   "url": "http://example.com/gallery3/index.php/rest/item/1",
   "entity": {
     "id": "1",
     "captured": null,
     "created": "1270793819",
     "description": "",
     "height": null,
     "level": "1",
     "mime_type": null,
     "name": null,
     "owner_id": "2",
     "rand_key": null,
     "resize_height": null,
     ...skipped some values to keep things short...
     "album_cover": "http://example.com/gallery3/index.php/rest/item/3",
     "thumb_url": "http://example.com/gallery3/var/thumbs//.album.jpg?m=1270958456"
   },
   "relationships": {
     "tags": {
       "url": "http://example.com/gallery3/index.php/rest/item_tags/1",
       "members": [
         "http://example.com/gallery3/index.php/rest/tag_item/9,1",
         "http://example.com/gallery3/index.php/rest/tag_item/10,1"
       ]
      }
    },
   "members": [
     "http://example.com/gallery3/index.php/rest/item/7",
     "http://example.com/gallery3/index.php/rest/item/11",
     "http://example.com/gallery3/index.php/rest/item/26"
   ]
 }

Browsing REST

If you are using Firefox, you can browse the responses of the REST interface in the following way. Download and install an extension to Firefox called ModifyHeaders (Go to Tools->Add-ons click Get Add-ons and go from there). Add the following two keys:

Name Value
X-Gallery-Request-Key (your REST key here)
X-Gallery-Request-Method GET

Your REST key is explained in the Security and Authentication section below. Then Browse for instance to the root Gallery album appending ?output=html to the end of the url. For instance: http://localhost/gallery3/index.php/rest/item/1?output=html

Working with the members collection

The members collection is an ordered list of members that's available on any collection resource. For example, an album is a collection and would have a members array (if the album has no members, the collection will be empty). A photo is not a collection and would not have a members array.

Two common operations for the members collection:

  • Delete a member
    • You can delete a member of a collection by using the DELETE verb on its url. What happens when you delete that member depends a little bit on what type of resource it is. If you delete an item resource (eg, a photo) then it's as if you deleted the photo via the web interface.
  • Reorder the members
    • If you pass back a members collection with the same members but in a different order, the collection will attempt to reorder the members. Note that not all collections are going to care about member order. For example, we probably don't care what order tags are in, but we do care about the display order of photos. Please refer to the docs for a collection for information about what happens when you reorder its members.

Working with the relationships collection

Each module can specify related resources, typically in the form of a collection of members. For example, the tags module specifies a list of tag_item members, each of which relates a single item to a single tag. By traversing that relationship, you can see all the tags which related to the current photo.

Relationships are read-only. You cannot change them directly by updating the current resource in the same way that you'd reorder members. You can only change them by interacting with their RESTful resources directly. So for example, if you want to un-tag an item you would not try to post a different relationship back to the current item, instead you'd use a DELETE verb directly on the tag_item relationship member resource.

Security and Authentication

The REST API follows all the same access permissions as the web based interface with one notable exception. Guest users cannot use the REST interface. This is an additional security measure designed to reduce the chance that a security bug in the REST code will expose your Gallery to external attacks.

Developer Tip: If you'd like to enable guest access to your REST API, you can go to Admin » Settings » Advanced and change the "allow_guest_access" parameter of the "rest" module from "0" to "1". This does not bypass application level security -- guests can't do anything that they can't already do via the web interface! But we don't recommend this mode in production because it increases your vulnerability if we make a privilege checking mistake in the REST code.

To access the REST interface, any requests you make must be accompanied by the X-Gallery-Request-Key HTTP header, which should contain a valid REST API key. Every registered Gallery user has a REST API key which is visible on their profile page (log in and click on your name in the top right of the web interface). This value uniquely identifies a Gallery user and grants all permissions you would normally have via the web interface.

We recommend that clients use the REST API key to avoid storing passwords in scripts. An API key can be invalidated or changed without changing the user's password. It's like a long-lived session token.

Example API key request

 GET /gallery3/index.php/rest/item/1 HTTP/1.1
 Host: example.com
 X-Gallery-Request-Method: get
 X-Gallery-Request-Key: 1114d4023d89b15ce10a20ba4333eff7

Example Login request

If you'd rather use a username/password, you can use the API itself to request an API key for future requests by sending a POST request to the main REST interface:

 POST /gallery3/index.php/rest HTTP/1.1
 Host: example.com
 X-Gallery-Request-Method: post
 Content-Type: application/x-www-form-urlencoded
 Content-Length: 25
 user=admin&password=12345

Note that you do not need to specify the X-Gallery-Request-Key header for this request. The response will contain a single json_encoded string value:

 HTTP/1.1 200 OK
 Content-Length: 34
 Content-Type: application/json
 "1114d4023d89b15ce10a20ba4333eff7"

Error handling

The API uses HTTP status codes to communicate the success or error of requests:

  • 200: success, the response body contains only the requested data (no status or success message)
  • 403: authorization failure, the body is generally empty (or the JSON empty array: []). This can happen in the following situations:
    • the username and password provided to the login method were incorrect
    • the X-Gallery-Request-Key was incorrect
    • no key was provided and the server was not set to accept unauthenticated requests
    • the entity is not readable (for GET requests) or writable (for POST/PUT/DELETE) by the user corresponding to the key
  • 400: other errors, the body may contain hints as to the nature of the error (but at the moment, details are a bit slim). This can happen in the following situations:
    • the REST resource doesn't exist (it may be provided by a module that's not enabled)
    • missing request parameters

Common URL Parameters

There is a small set of parameters that you can append to any RESTful URL which will affect all REST operations. These are designed to be part of the Gallery REST framework. Individual resource types may specify their own query parameters.


GET requests
Query parameters
Parameter Description
output By default the output format for all responses is JSON. There are three legal output formats:
  • output=html : the response will come back in HTML that you can view in your web browser. This is very convenient as a developer if you want to browse around the various REST collections in your Gallery.
  • output=jsonp : this will wrap the JSON according to the JSONP standard. You must also specify a callback value eg. callback=parseData
  • output=json : the response will come back as JSON data.
num The number of members to return as part of this request. Max is 100. To retrieve more than 100, you must use the start parameter.
start The index of the first member to retrieve. This is zero based, so to get the first member specify "start=0" (which is also the default). If you want to retrieve members in blocks of 100, specify "start=0&num=100" on the first request, then "start=100&num=100" and keep incrementing start by 100 until you get back less than 100 members (that'll be the last request).

Common REST resources

The official Gallery code comes with REST support for a variety of common objects. The REST framework makes it relatively easy for core and 3rd party developers to add more REST support.

Items

This is a read-only collection of all items, for query purposes only. In order to use it, you must make a GET request and specify query parameters to specify which resources you'd like to get back. You'll receive back a list of resources.

GET requests
Query parameters
Parameter Description
urls The value of this parameter should be a json encoded list of REST urls. The members collection will contain a JSON encoded list of REST urls to return. Example:

GET /gallery3/index.php/rest/items?urls=["http://example.com/gallery3/index.php/rest/item/3","http://example.com/gallery3/index.php/rest/item/5"]

ancestors_for Return a list of all the ancestors for a given item. This is useful if you want to build a breadcrumb trail for an item. If you specify both ancestors_for and url in the same query, ancestors_for is ignored. Example:

GET /gallery3/index.php/rest/items?ancestors_for=http://example.com/gallery3/index.php/rest/item/26

type This restricts the results to items of the given type. Legal values are "photo", "movie" or "album". This parameter is ignored if the ancestors_for parameter is present.

Item

This is a read/write resource that represents a single item (photo, album or movie) in the Gallery.

GET requests

Example: GET /gallery3/index.php/rest/item/1

Query parameters
Parameter Description
scope This parameter controls which members you get in response to a query. Legal values are "direct" and "all". The default value is "direct" which only returns members that are immediate children of the given item. "all" will return all descendants so use this with care on large installations. Can be used in combination with any other parameter.
name Restrict the member responses only to items that contain the value as a substring of the name. Can be used in combination with any other parameter.
random Return a single random item. Legal value is "true". Can be used in combination with any other parameter.
type Restrict results to items of the given time. Legal values are "photo", "movie" and "album". Can be used in combination with any other parameter.
PUT requests

You can modify any value in the entity resource. If the value you change it to is illegal, you'll receive a Bad Request response in return.

  • Moving an album
    • Set the "parent" field to the REST resource for the new parent
  • Reordering children
    • Modify the order of the URLs in the members collection. Note that attempts to add or remove a member this way will be ignored. Also, you must set the value of sort_column to "weight" for this to take effect.
DELETE requests

You can DELETE any resource, same as you would via the web interface. If you don't have permissions to perform the delete operation, you'll receive a Bad Request response in return.

CREATE requests

The "type" and "name" are required fields for all new items. When creating a photo or a movie, you must also pass in a "file" POST parameter containing a multipart/mime image or movie file.


Tags

No docs yet.

Tag

No docs yet.

Comments

No docs yet.

Comment

No docs yet.

Client libraries

PHP

The Gallery team provides a PHP client library along with some example code: https://github.com/gallery/gallery3-contrib/tree/master/3.0/client . Note that this is not officially supported currently and is subject to change. We'll do our best to keep it updated though, and any feedback you can provide here would be very useful.

Creating a REST resource

Any module can define a REST resource simply by creating a xxx_rest.php helper class. That class will handle any requests to resources named xxx. Each REST handler can handle one or all of the following responsibilities:

  • resolve (required)
    • The handler is responsible for providing a way to turn a REST url (eg: http://example.com/gallery3/index.php/rest/item/1) into one or more Gallery 3 objects. In most cases it's just converting a single url into a single object, but in some cases you might want to return a tuple, for example if the URL refers to a relationship and you want to resolve both sides of it at once.
  • url (required)
    • The handler is responsible for providing a way to turn one or more objects into their corresponding REST url.
  • GET, PUT, POST and DELETE (optional)
    • The handler can implement any or all of these, but is is responsible for doing access level permission checks to make sure that the user has the privilege to perform the operation. For GET requests, the handler can define and support its own query parameters.
  • relationships
    • The handler can provide a set of related resources applicable to the given resource. Generally this requires the handler to know what type of resource it's receiving and do something sane.

Once you create the helper class in an activated module, it's immediately available for use. It doesn't need to be registered.

Example implementations

http://github.com/gallery/gallery3/blob/master/modules/rest/helpers/registry_rest.php

A list of all avaialble REST services. GET only

http://github.com/gallery/gallery3/blob/master/modules/gallery/helpers/items_rest.php

All items. GET only

http://github.com/gallery/gallery3/blob/master/modules/gallery/helpers/item_rest.php

An individual item. GET, PUT, POST, DELETE

http://github.com/gallery/gallery3/blob/master/modules/gallery/helpers/data_rest.php

Data and metadata for thumbnails, resizes and full sized images. GET only.

http://github.com/gallery/gallery3/blob/master/modules/tag/helpers/tag_rest.php

An individual tag. GET, PUT, DELETE and relationships

http://github.com/gallery/gallery3/blob/master/modules/tag/helpers/tags_rest.php

All tags. GET, POST, DELETE

http://github.com/gallery/gallery3/blob/master/modules/tag/helpers/tag_item_rest.php

A tag / item relationship. GET, DELETE

http://github.com/gallery/gallery3/blob/master/modules/tag/helpers/tag_items_rest.php

All the items for a tag. GET, POST, DELETE

http://github.com/gallery/gallery3/blob/master/modules/tag/helpers/item_tags_rest.php

All the tags for an item. GET, POST, DELETE

http://github.com/gallery/gallery3/blob/master/modules/comment/helpers/comments_rest.php

All comments. GET, POST and relationships

http://github.com/gallery/gallery3/blob/master/modules/comment/helpers/comment_rest.php

A single comment. GET, PUT, DELETE

http://github.com/gallery/gallery3/blob/master/modules/comment/helpers/item_comments_rest.php

All the comments for an item. GET