Skip to content

Instantly share code, notes, and snippets.

@velsa
Created October 2, 2014 12:53
Show Gist options
  • Save velsa/ec237a8559cbe6b27433 to your computer and use it in GitHub Desktop.
Save velsa/ec237a8559cbe6b27433 to your computer and use it in GitHub Desktop.
VIBOTV Backend API

TODO:

  • No todo list yet...

Для доступа к URLs, используется CRUD (Create/Read/Update and Delete):

  • Create через HTTP POST request.
  • Read через HTTP GET request.
  • Update через HTTP PUT request.
  • Delete через HTTP DELETE request.

Все Create (POST) и Update (PUT) запросы должны содержать JSON обьект с соответствующим полем :noun.

Все ответы содержат аналогичный JSON обьект с соответствующим полем :noun. Поля в этом обьекте заполняются бекендом в соответствии с запросом.

Также, запросы и ответы содержат вспомогательные поля meta и notifications:

  • Поле meta содержит вспомогательную информацию, отражающую запрос.
  • Поле notifications содержит список тесктовых сообщений для пользователя. Клиент может показать эти сообщения пользователю где и когда посчитает нужным.

Все поля datetime, передающиеся в запросах, всегда должны быть в ISO 8601 формате. На данный момент, поддерживается только ОДИН вариант репрезентации даты и времени из стандарта 8601:

yyyy-mm-ddThh:mm:ss-hh:mm

Например, формат Московского времени будет выглядеть так: 2014-01-19T02:00:00-04:00

Корректность передаваемого параметра datetime можно проверить следующим regexp:

/^\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}(?:\-\d{2}\:\d{2})?$/


HTTP Response codes:

Success:

| Code | Description | | ------ | --------- | ----------- | | 200 | GET or PUT request completed successfully. Body of the reply contains requested or updated data. | | 201 | POST request completed successfully. Body of the reply is empty (No contet). | | 204 | DELETE or PUT request completed successfully. Body of the reply is empty (No contet). |

Error handling:

Errors are returned using standard HTTP error code syntax. Any additional info is included in the body of the return call, JSON-formatted. Error codes not listed here are in the REST API methods listed below.

| Code | Description | | ------ | --------- | ----------- | | 400 | Bad input parameter. Error message should indicate which one and why. | | 403 | Bad OAuth request (wrong consumer key, bad nonce, expired timestamp...). Unfortunately, re-authenticating the user won't help here. | | 404 | Object not found. Returned when the specified :noun_id is not found in database. | | 405 | Request method not expected (generally should be GET, POST, PUT or DELETE). | | 429 | Your app is making too many requests and is being rate limited. 429s can trigger on a per-app or per-user basis. | | 500 | Internal Server error. | | 503 | If the response includes the Retry-After header, this means your OAuth 1.0 app is being rate limited. Otherwise, this indicates a transient server error, and your app should retry its request. | | 507 | User is over storage quota. |


Format of nouns in URLs and in JSON requests and responses

URLs всегда компонуются из :noun_plural.

:noun_plural - это любая из сущностей во МНОЖЕСТВЕННОМ числе:

portals, channels, contents
series, seasons, episodes
shows, movies, news
infos, persons, images, tags, web_links, web_urls

Для JSON данных в Create (POST), Update (PUT) и Delete (DELETE) запросах и ответах используется :noun.

:noun - это любая из сущностей в ЕДИНСТВЕННОМ числе:

portal, channel, content
serie, season, episode
show, movie, newscast
info, person, image, tag, web_link, web_url

Reading objects


Get list of Portals:

GET http://api.srv/1.0/portals?arg1=val1&arg2=val2...
Argument Default Description
offset=int 0 Skip this number of Portals
limit=int 10 Limit output to this number of Portals
sort=string name Sort portals by specified field. Default sort order is ASCENDING. Add - in front of the field to set DESCENDING sort order
ids=portal_id,portal_id,... none Get only portals with specified portal_id's
types=portal_type,portal_type,... none Get only portals with specified portal_type's
tags=tag_name,tag_name,... none Get Portals with any of the specified tags
access=access_id,access_id,... none Get Portals with any of the specified access rights
fields=field,field,... none JSON response will contain only the specified fields. NOTE: id is always returned in the response. You can also specify field names with - at the beginning, to exclude specific fields from JSON response.
// JSON Response
{
    'meta': {
        'offset': int,
        'limit': int,
        'total': int,
        'sort': '...',
        'order': '...',
        'ids': '...',
        'types': '...',
        'tags': '...',
        'access': '...',
        'fields': '...'
    },
    'portals': [
        {
            'id': '...',                        // ':portal_id'
            'info': {...},                      // Info about Portal, see Info_Schema
            'tags': ['tag_name', ...],          // Tags for this Portal
            'access': [':access_id', ... ],     // Access rights for this Portal

            'type': '...'                       // 'manual' / 'youtube' / 'youtube_public' /
                                                // 'facebook' / 'vk' / ...
        },
        ...
    ],
    'notifications': [ '...', ... ]             // Some textual notifications for the user
}

Get list of Channels from Portal(s):

GET http://api.srv/1.0/channels?arg1=val1&arg2=val2...
Argument Default Description
portal_ids=portal_id,portal_id,... none Get channels from specified portals only
offset=int 0 Skip this number of channels. If portal_ids are specified, offset will skip the specified number of channels for EACH PORTAL.
limit=int 10 Limit output to this number of channels. If portal_ids are specified, limit will limit the number of channels per portal. NOTE: This means, that the TOTAL number of channels in response may be GREATER than specified limit !
sort=string modified Sort channels by specified field. Default sort order is ASCENDING. Add - in front of the field to set DESCENDING sort order
ids=channel_id,channel_id,... none Get channels with specified channel_id's only
types=channel_type,channel_type,... none Get only channels with specified channel_type's
age_from=int none Get channels with age_restriction more than or equal to specified age. If age_till is NOT specified, will also include channels with age_restriction = 0
age_till=int none Get channels with age_restriction less than or equal to specified age. Will NOT include channels with age_restriction = 0
tags=tag_name,tag_name,... none Get channels with any of the specified tags
access=access_id,access_id,... none Get channels with any of the specified access rights
auth=string none User authentication token (from OAuth 2.0) to get user specific channels from portal
fields=field,field,... none JSON response will contain only the specified fields. NOTE: only top level fields can be selected (e.g. info.name can't be a field, but info can). Also, id is always returned in the response. You can also specify field names with - at the beginning, to exclude specific fields from JSON response
// JSON Response
{
    'meta': {
        'portal_ids': '...',
        'offset': int,
        'limit': int,
        'total': int,
        'sort': '...',
        'order': '...',
        'ids': '...',
        'types': '...',
        'age_from': int,
        'age_till': int,
        'tags': '...',
        'access': '...',
        'fields': '...'
    },
    'channels': [
        {
            'id': '...',                        // ':channel_id'
            'portal_id': '...',                 // ':portal_id'

            'type': String,                     // Channel type (e.g. 'tv' for all TV channels)
            'age_restriction': Number,          // Age restriction for this content
                                                // (0 - no restriction)

            'info': {...},                      // Info about channel, see Info_Schema
            'tags': ['tag_name', ...],          // Tags for this channel
            'access': [':access_id', ... ],     // Access rights for this channel

            'added': Date,                      // datetime the channel was created
            'modified': Date,                   // datetime of the most recently updated
                                                // content in channel

            'streams:' [                        // Playable streams for this Channel
                {                               // E.g.: live broadcast for TV channels
                                                // or promo video for portals
                    // see Stream_Schema
                },
                ...
            ]
        },
        ...
    ],
    'notifications': [ '...', ... ]             // Some textual notifications for the user
}

Get list of Content in Channel(s):

GET
http://api.srv/1.0/contents/?arg1=val1&arg2=val2...
Argument Default Description
channel_ids=channel_id,channel_id,... none Get contents from specified channels only
offset=int 0 Skip this number of content items. If channel_ids are specified, offset will skip the specified number of content items for EACH CHANNEL.
limit=int 10 Limit output to this number of content items. If channel_ids are specified, limit will limit the number of content items per channel. NOTE: This means, that the TOTAL number of content items in response may be GREATER than specified limit !
sort=string modified Sort portal contents by specified field. Default sort order is ASCENDING. Add - in front of the field to set DESCENDING sort order
order=string desc
ids=content_id,content_id,... none Get content with specified content_id's only
types=content_type,content_type,... none Get only contents with specified type's
age_from=int none Get content with age_restriction more than or equal to specified age. If age_till is NOT specified, will also include content with age_restriction = 0
age_till=int none Get content with age_restriction less than or equal to specified age. Will NOT include content with age_restriction = 0
tags=tag_name,tag_name,... none Get content with any of the specified tags
persons=person_id,person_id,... none Get content with any of the specified persons
live=true/false none Get only live or only NON live content
content_type=string none Get content with the specified type. Can be one of the following: episode, show, movie, news, other
recommended=string none Allows to get only recommended content with specified type of recommendation: vibotv, provider
duration_from=int 0 Get content with duration more than or equal to specified duration (in SECONDS)
duration_to=int 0 Get content with duration less than or equal to specified duration (in SECONDS)
auth=string none User authentication token (from OAuth 2.0) to get user specific content info
fields=field,field,... none JSON response will contain only the specified fields. NOTE: id is always returned in the response. You can also specify field names with - at the beginning, to exclude specific fields from JSON response

Searching:

Argument Default Description
q=query_string none Filters contents by searching the name and description fields for the specified query
q_type=match/exact/regex match Search query is match, exact match (exact) or regular expression

TV content:

Argument Default Description
airing=string none Get content with the specified airing type: original or repeat
start_from=datetime none Get content which start's on or after the specified datetime
start_till=datetime none Get content which start's on or before the specified datetime
end_from=datetime none Get content which end's on or after the specified datetime
end_till=datetime none Get content with end's on or before the specified datetime

Non TV content:

Argument Default Description
added_from=datetime none Get content that was added on or after the specified datetime
added_till=datetime none Get content that was added on or before the specified datetime
modified_from=datetime none Get content that was modified on or after the specified datetime
modified_till=datetime none Get content that was modified on or before the specified datetime
// JSON Response
{
    'meta': {
        'channel_ids': '...',

        'offset': int,
        'limit': int,
        'total': int,
        'sort': '...',
        'order': '...',
        'ids': '...',
        'types': '...',
        'age_from': int,
        'age_till': int,
        'tags': '...',
        'persons': '...',
        'live': true/false,
        'content_type': '...',
        'recommended': '...',

        // TV content
        'airing': '...',
        'start_from': '...',
        'start_till': '...',
        'end_from': '...',
        'end_till': '...',

        // Non TV content
        'added_from': '...',
        'added_till': '...',
        'modified_from': '...',
        'modified_till': '...',

        'duration_from': int,
        'duration_to': int,
        'fields': '...',
    },
    'contents': [
        {
            'id': '...',                        // ':content_id'
            'channel_id': '...',                // ':channel_id'
            'portal_id': '...',                 // ':portal_id'

            'info': {...},                      // Info about content, see Info_Schema
            'tags': ['tag_name', ...],          // Tags for this content
            'persons': ['person_id', ...],      // Persons for this content

            'type': String,                     // Content type (e.g. 'tv' for TV content)
            'age_restriction': Number,          // Age restriction for this content
                                                // (0 - no restriction)
            'live': Boolean,                    // true if this is a live broadcast
            'meta_type': '...',                 // 'episode', 'show', 'movie', 'news', 'other'
            'content_meta': {...},              // Contains meta info for the 'type'
                                                // will depend of specific portal
            'recommended': String,              // null if recommendation does not exist
                                                // or 'vibotv', 'provider'
                                                // if recommended by us or provider

            // TV Content
            'airing': '...',                    // 'original' / 'repeat'
            'start': Date,                      // Start datetime
            'end': Date,                        // End datetime

            // Non TV Content
            'added': Date,                      // datetime the content was added to portal
            'modified': Date,                   // datetime the content was modified in portal

            'duration': int,                    // Duration in SECONDS

            'streams:' [                        // Playable streams for this Portal Content
                {
                    // see Stream_Schema
                },
                ...
            ]
        },
        ...
    ],
    'notifications': [ '...', ... ]             // Some textual notifications for the user
}

Creating, Updating and Deleting objects


URLs for Main and Helper objects:

Portals:

BASE URL: http://api.srv/1.0

Object Create (POST) Update (PUT) and Delete (DELETE)
Portal /portals /portals/:portal_id
Channel /channels /channels/:channel_id
Content /contents /conents/:content_id

Series (Сериалы)

BASE URL: http://api.srv/1.0/series

Object Create (POST) Update (PUT) and Delete (DELETE)
Series / /:serie_id
Seasons /:serie_id/seasons /:serie_id/seasons/:season_id
Episodes /:serie_id/seasons/:season_id/episodes /:serie_id/seasons/:season_id/episodes/:episode_id

JSON Requests and Responses

Create (POST):

// JSON Request
{
    'meta': {},
    ':noun': {
        // fields from corresponding ':noun_plural' MongoDB Schema
        ...
    }
}

// JSON Response
{
    'meta': {},
    ':noun': {
        'id': '...',                            // unique id, generated by backend server

        // fields from corresponding ':noun_plural' MongoDB Schema
        ...
    },
    'notifications': [ '...', ... ]
}

Update (PUT):

// JSON Request
{
    'meta': {},
    ':noun': {
        // fields that need modification
        // see corresponding ':noun_plural' MongoDB Schema
        ...
    }
}

// JSON Response
{
    'meta': {},
    ':noun': {
        'id': '...',

        // fields from corresponding ':noun_plural' MongoDB Schema
        ...
    },
    'notifications': [ '...', ... ]
}

Delete (DELETE):

// JSON Request
{
    'meta': {}
}

// JSON Response
{
    'meta': {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment