JSON API

MediaDrop provides a simple API for grabbing media info. A GET request to any of the public methods on this page will return a JSON object with the returned information.

MediaDrop’s controllers render JSON objects by preparing what we call a JSON-ready dict. In these dicts, all keys are Python’s unicode type and all values are of a type in the table below. There there is a 1-1 mapping between Python types and JavaScript types:

Python JavaScript
dict Object
list Array
unicode String
int Number
float Number
bool Boolean
None null

API KEYS: It is up to the administrator of a MediaDrop site to allow or disallow public access to that site’s API. To this end, an administrator can choose to require an API Key be sent with every API request. This key is configurable in MediaDrop’s Admin -> Settings -> Data API page.

Querying Media Items

MediaDrop provides a get method for returning information about an individual media item (given an id or slug) and an index method for returning information on a list of media items that match specified criteria.

Both of these methods make use of the media_info dicts provided by the private _info method.

MediaController._info(media, podcast_slugs=None, include_embed=False)

Return a media_info dict–a JSON-ready dict for describing a media instance.

Return type:JSON-ready dict
Returns:The returned dict has the following fields:
author (unicode)
The name of the author of the media instance.
categories (dict of unicode)
A JSON-ready dict representing the categories the media instance is in. Keys are the unique slugs for each category, values are the human-readable title of that category.
id (int)
The numeric unique id of the media instance.
slug (unicode)
The more human readable unique identifier (slug) of the media instance.
url (unicode)
A permalink (HTTP) to the MediaDrop view page for the media instance.
embed (unicode)
HTML code that can be used to embed the video in another site.
title (unicode)
The title of the media instance.
type (string, one of [‘audio’, ‘video’])
The type of the media instance
podcast (unicode or None)
The slug of the podcast that the media instance has been published under, or None
description (unicode)
An XHTML description of the media instance.
description_plain (unicode)
A plain text description of the media instance.
comment_count (int)
The number of published comments on the media instance.
publish_on (unicode)
The date of publishing in “YYYY-MM-DD HH:MM:SS” (ISO 8601) format. e.g. “2010-02-16 15:06:49”
likes (int)
The number of like votes that the media instance has received.
views (int)
The number of views that the media instance has received.
thumbs (dict)
A dict of dicts containing URLs, width and height of different sizes of thumbnails. The default sizes are ‘s’, ‘m’ and ‘l’. Using medium for example:
medium_url = thumbs['m']['url']
medium_width = thumbs['m']['x']
medium_height = thumbs['m']['y']

Single Media Items

If you know the id or slug of a single media item you want to query, use the get method (available by default at /api/media/get).

Examples:

MediaController.get(*args, **kwargs)

Expose info on a specific media item by ID or slug.

Parameters:
  • id (int) – An id for lookup
  • slug (str) – A slug for lookup
  • api_key (unicode or None) – The api access key if required in settings
Raises webob.exc.HTTPNotFound:
 

If the media doesn’t exist.

Return type:

JSON-ready dict

Returns:

The returned dict is a media_info dict, generated by the _info method.

Lists of Media Items

To return a filtered list of media info, use the index method (available by default at /api/media).

Examples:

MediaController.index(*args, **kwargs)

Query for a list of media.

Parameters:
  • type – Filter by ‘audio’ or ‘video’. Defaults to any type.
  • podcast – A podcast slug (or slugs) to filter by. Use 0 to include only non-podcast media or 1 to include any podcast media. For multiple podcasts, separate the slugs with commas.
  • tag – A tag slug to filter by.
  • category – A category slug to filter by.
  • search – A boolean search query. See http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html
  • published_after – If given, only media published on or after this date is returned. The expected format is ‘YYYY-MM-DD HH:MM:SS’ (ISO 8601) and must include the year at a bare minimum.
  • published_before – If given, only media published on or before this date is returned. The expected format is ‘YYYY-MM-DD HH:MM:SS’ (ISO 8601) and must include the year at a bare minimum.
  • max_age (int) – If given, only media published within this many days is returned. This is a convenience shortcut for publish_after and will override its value if both are given.
  • min_age (int) – If given, only media published prior to this number of days ago will be returned. This is a convenience shortcut for publish_before and will override its value if both are given.
  • order – A column name and ‘asc’ or ‘desc’, seperated by a space. The column name can be any one of the returned columns. Defaults to newest media first (publish_on desc).
  • offset (int) – Where in the complete resultset to start returning results. Defaults to 0, the very beginning. This is useful if you’ve already fetched the first 50 results and want to fetch the next 50 and so on.
  • limit (int) – Number of results to return in each query. Defaults to 10. The maximum allowed value defaults to 50 and is set via request.settings['api_media_max_results'].
  • featured (bool) – If nonzero, the results will only include media from the configured featured category, if there is one.
  • include_embed (bool) – If nonzero, the HTML for the embeddable player is included for all results.
  • id (int or None) – Filters the results to include the one item with the given ID. Note that we still return a list.
  • slug (unicode or None) – Filters the results to include the one item with the given slug. Note that we still return a list.
  • api_key (unicode or None) – The api access key if required in settings
Raises APIException:
 

If there is an user error in the query params.

Return type:

JSON-ready dict

Returns:

The returned dict has the following fields:

count (int)

The total number of results that match this query.

media (list of dicts)

A list of media_info dicts, as generated by the _info method. The number of dicts in this list will be the lesser of the number of matched items and the requested limit. Note: unless the ‘include_embed’ option is specified, The returned media_info dicts will not include the ‘embed’ entry.

Querying Media Files

MediaDrop provides a files method for returning information about the mediadrop.model.media.MediaFile instances associated with a given mediadrop.model.media.Media instance.

This method makes use of the file_info dicts provided by the private _file_info method.

MediaController._file_info(file, media)

Return a file_info dict–a JSON-ready dict for describing a media file.

Return type:JSON-ready dict
Returns:The returned dict has the following fields:
container (unicode)
The file extension of the file’s container format.
type (unicode)
The file type. One of (‘video’, ‘audio’, ‘audio_desc’, ‘captions’) or a custom type defined in a plugin.
display_name (unicode)
The display_name of the file. Usually the original name of the uploaded file.
created (unicode)
The date/time that the file was added to MediaDrop, in “YYYY-MM-DDTHH:MM:SS” (ISO 8601) format. e.g. “2011-01-04T16:23:37”
url (unicode)
A permalink (HTTP) to the MediaDrop view page for the media instance associated with this file.
uris (list of dicts)
Each dict in this list represents a URI via which the file may be accessible. These dicts have the following fields:
scheme (unicode)
The scheme (e.g. ‘http’ in the URI ‘http://mediadrop.net/docs/‘, ‘rtmp’ in the URI ‘rtmp://mediadrop.net/docs/’, or ‘file’ in the URI ‘file:///some/local/file.mp4’)
server (unicode)
The server name (e.g. ‘mediadrop.net’ in the URI ‘http://mediadrop.net/docs‘)
file (unicode)
The file path part of the URI. (e.g. ‘docs’ in the URI ‘http://mediadrop.net/docs‘)
uri (unicode)
The full URI string (minus scheme) built from the server_uri and file_uri. See mediadrop.lib.uri.StorageUri.__str__. (e.g. ‘mediadrop.net/docs’ in the URI ‘http://mediadrop.net/docs‘)

Lists of Media Files

When you know the id or slug of a single media instance that you want to get the file info for, files method (available by default at /api/media/files).

Examples:

MediaController.files(*args, **kwargs)

List all files related to specific media.

Parameters:
Raises webob.exc.HTTPNotFound:
 

If the media doesn’t exist.

Return type:

JSON-ready dict

Returns:

The returned dict has the following fields:

files

A list of file_info dicts, as generated by the _file_info method.

Querying Categories

MediaDrop provides two methods of listing categories: index for listing all categories in a flat list, and tree for listing all categories in the hierarchy tree.

Both of these methods make use of the category_info dicts provided by the private _info method.

CategoriesController._info(cat)

Return a JSON-ready dict representing the given category instance.

Return type:JSON-Ready dict
Returns:The returned dict has the following fields:
id (int)
The numeric unique identifier, Category.id
slug (unicode)
The more human readable unique identifier, Category.slug
name (unicode)
The human readable name of the category.
parent (unicode or None)
the slug of the category’s parent in the hierarchy, or None.
media_count (int)
The number of media items that are published in this category, or in its sub-categories.

Lists of Categories

To query a flat list of categories, use the index method (available by default at /api/categories).

Examples:

CategoriesController.index(*args, **kwargs)

Query for a flat list of categories.

Parameters:
  • id (int) – An id for lookup
  • name (str) – A name for lookup
  • slug (str) – A slug for lookup
  • order (str) – A column name and ‘asc’ or ‘desc’, seperated by a space. The column name can be any one of the returned columns. Defaults to newest category first (id desc).
  • offset (int) – Where in the complete resultset to start returning results. Defaults to 0, the very beginning. This is useful if you’ve already fetched the first 50 results and want to fetch the next 50 and so on.
  • limit (int) – Number of results to return in each query. Defaults to 10. The maximum allowed value defaults to 50 and is set via request.settings['api_media_max_results'].
  • api_key (unicode or None) – The api access key if required in settings
Return type:

JSON-ready dict

Returns:

The returned dict has the following fields:

count (int)

The total number of results that match this query.

categories (list of dicts)

A list of category_info dicts, as generated by the _info method. The number of dicts in this list will be the lesser of the number of matched items and the requested limit.

Hierarchies of Categories

To query a hierarchy of categories, use the tree method (available by default at /api/categories/tree).

Examples:

CategoriesController.tree(*args, **kwargs)

Query for an expanded tree of categories.

Parameters:
  • id (int) – A mediadrop.model.media.Category.id to lookup the parent node
  • name (str) – A mediadrop.model.media.Category.name to lookup the parent node
  • slug (str) – A mediadrop.model.media.Category.slug to lookup the parent node
  • depth – Number of level deep in children to expand. Defaults to 10. The maximum allowed value defaults to 10 and is set via request.settings['api_tree_max_depth'].
  • api_key (unicode or None) – The api access key if required in settings
Return type:

JSON-ready dict

Returns:

The returned dict has the following fields:

count (int)

The total number of results that match this query.

categories (list of dicts)

A list of category_info dicts, as generated by the _info method. Each of these dicts represents a category at the top level of the hierarchy. Each dict has also been modified to have an extra ‘children’ field, which is a list of category_info dicts representing that category’s children within the hierarchy.

Python Example

The following Python code fetches the first 6 videos published in February, 2011, and outputs a simple HTML snippet with a thumbnail, title, link, and short description of each video.

import urllib
try:
   import json # py26
except:
   import simplejson as json # py25 and under

api_url = 'http://demo.getmediacore.com/api/media'
api_key = 'zPDyJXdjrPgmFxHC1xw'
excerpt_length = 180

def fetch_media_list(**kwargs):
   kwargs['api_key'] = api_key
   querystring = urllib.urlencode(kwargs)
   f = urllib.urlopen(api_url + '?' + querystring)
   return json.loads(f.read())

def truncate(text):
   if len(text) > excerpt_length:
      right = text[:excerpt_length].rindex(' ')
      text = text[:right] + '…'
   return text

result = fetch_media_list(
   type='video',
   published_after='2011-02-01 00:00:00',
   limit=6
)
videos = result['media']

output = ["<h1>Previews:</h1>"]

for v in videos:
   output.append(
      '<div><a href="%s"><img src="%s" alt="%s"/>%s</a>%s</div>' % (
         v['url'], v['thumbs']['s']['url'], v['title'], v['title'],
         truncate(v['description_plain'])
      )
   )

print '\n'.join(output)

PHP Example

The following PHP code fetches the first 6 videos published in February, 2011, and outputs a simple HTML snippet with a thumbnail, title, link, and short description of each video.

<?php
   $media_api = 'http://demo.getmediacore.com/api/media';
   $api_key = 'zPDyJXdjrPgmFxHC1xw';
   $excerpt_length = 180;

   function fetch_media_list($data) {
      global $media_api, $api_key;

      $data['api_key'] = $api_key;
      $uri = $media_api . '?' . http_build_query($data);
      return json_decode(file_get_contents($uri));
   }

   function truncate($text) {
      global $excerpt_length;

      if (strlen($text) > $excerpt_length) {
         $left = 0;
         $right = strrpos(substr($text, 0, $excerpt_length-1), ' ');
         $text = substr($text, $left, $right) . '&hellip;';
      }
      return $text;
   }

   $result = fetch_media_list(array(
      'type' => 'video',
      'published_after' => '2011-02-01%2000:00:00',
      'limit' => 6
   ));
   $videos = $result->media;
?>

<h1>Previews:</h1>
<?php foreach ($videos as $video): ?>
   <div>
      <a href="<?php echo $video->url; ?>">
         <img src="<?php echo $video->thumbs->s->url; ?>"
             alt="<?php echo $video->title; ?>" />
         <?php echo $video->title; ?>
      </a>
      <?php echo truncate($video->description_plain); ?>
   </div>
<?php endforeach ?>
You're reading the documentation for MediaDrop 0.11dev (current git master). For the latest stable release please consult the documentation for MediaCore CE 0.10.