How to use Nicovideo's Contents Search API

Tommy Teasdale

 November 18, 2016
  Apiニコニコ動画Nicovideo


The Content Search API allows to search content on Nicovideo from third-party applications. This tutorial will show how to easily retrieve search results using PHP.

On March 17th, 2017 the official documentation of the API has been removed. On May 20th the documentation has moved to http://site.nicovideo.jp/search-api-docs/search.html

API Documentation

URL Parameter

The generic endpoint of the API is http://api.search.nicovideo.jp/api/v2/:service/contents/search. The API can be called to retrieve information from the following services:

Service API Service Name
動画 video
生放送 live
静画(イラスト) illust
静画(マンガ) manga
静画(書箱) book
チャンネル channel
ブロマガ channelarticle
ニューズ news

Replace :service with the name of a service.

Query Arguments

The options of the search request are encoded using query arguments through the GET method.

Mandatory Arguments

  • q : Search Keywords
  • targets : Search Objects (Separated by a comma, one or many of the following: title, tags, description and tagsExact)
  • fields : Content Fields of the hits returned (Separated by a comma, one or many of the following: contentId, title, description, tags, categoryTags, viewCounter, mylistCounter, commentCounter, startTime, communityIcon, liveStatus)
  • _sort : Sort Method (' ' or '-' for the order, one of the following : viewCounter, mylistCounter, commentCounter, startTime, thumbnailUrl, scoreTimeshiftReserved)

Optionial Arguments

  • filters : Search Filters (The following fields can be used to filter: contentId, tags, categoryTags, viewCounter, mylistCounter, commentCounter, startTime, liveStatus)
  • _limit : Number of hits returned (10 by default, 100 maximum)
  • _offset : Number of hits skipped (0 by default, 1600 maximum)
  • _context : Service/Application Name (Maximum length of 40 characters)

Response

The API will return the following JSONs.

On success

Field Name Type Description
meta object Information about the response
meta.status integer HTTP Status Code (200 on success)
meta.id string Request Identifier
meta.totalCount integer Total number of hits
data array Content of the hits. Contains the values of the fields specified in the fields parameter of the query.

On failure

Field Name Type Description
meta object Information about the response
meta.status integer HTTP Status Code
meta.errorCode string Code of the error encountered
meta.errorMessage string Description of the error

Example Application

We are going to write a simple application to retrive the most recent pictures of Miku Hatsune and generate a small gallery.

First, we gather the url and the options.

$basic_url = "http://api.search.nicovideo.jp/api/v2/:service/contents/search";
$options = [
    "q" => "初音ミク",                  // Search Keyword
    "targets" => "title,tags",         // Search Object
    "fields" => "contentId,title,tags",// Fields of the hits returned
    "_sort" => "-startTime",           // Sort Method
    "_limit" => 12,                    // Number of hits returned
    "_offset" => 0,                    // Number of hits skipped
    "_context" => "apiguide"           // Service/Application Name
];

Then replace :service with the name of the desired service.

$url = str_replace(":service", "illust", "http://api.search.nicovideo.jp/api/v2/:service/contents/search");

Assemble the query parameters from the array and execute the query.

$parameters = "?";
$ctr = 1;
$length = count($options);
foreach ($options as $name => $value) {
    $parameters .= $name . "=" . urlencode($value);

    if ($ctr < $length) {
        $parameters .= &#39;&&#39;;
    }
    $ctr  ;
}

$request = $url . $parameters;
$response = file_get_contents($request);
$json_response = json_decode($response);

if (json_last_error() !== JSON_ERROR_NONE) {
    die(json_last_error_msg());
} else {
    if (isset($json_response->meta)) {
        if ($json_response->meta->status == 200) {
            // Success
        } else {
            // Failure
        }
    } else {
        // Failure
    }
}

The query string produced will be similar to this :

http://api.search.nicovideo.jp/api/v2/illust/contents/search?q=初音ミク&targets=title,tags&fields=contentId,title,tags&_sort=-startTime&_limit=12&_offset=0&_context=apiguide

The response must be a JSON object otherwise the query has failed. If the status is 200 the query is successful and therefore you can parse the results.

$data = array();

foreach ($json_response->data as $item) {
    $data[] = (object) (array) $item;
}

$total = $json_response->meta->totalCount;

Now you can invoke a view to display the results. Here's an example view for this example. It will print the thumbnail of the illustration with a link to visit the page on niconico Seiga.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Nicovideo Contents Search API Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
    <div class="row">
        <?php foreach ($data as $item) : ?>
            <div class="col-xs-6 col-sm-3 col-md-2">
                <a class="thumbnail" href="<?= "http://seiga.nicovideo.jp/image/source/" . preg_replace("/[^0-9]/", "", $item->contentId) ?>" target="_blank">
                    <img title="<?= $item->title ?>" src="<?= str_replace(":img_num_id", preg_replace("/[^0-9]/", "", $item->contentId), ""http://lohas.nicoseiga.jp/thumb/:img_num_idcz") ?>" style="width:100%">
                </a>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

See A More Complete Example


For more documentation on the API and more advanced features like filters, view the official documentation in Japanese of the API here : http://search.nicovideo.jp/docs/api/search.html

Share this on Social Media


 Share

 Tweet

 Post

 Share

Comments


There is no comment for the moment