快速入門:使用 Bing 影片搜尋 REST API 和 Node.js 來搜尋影片Quickstart: Search for videos using the Bing Video Search REST API and Node.js

使用本快速入門來進行您對 Bing 影片搜尋 API 的第一次呼叫,並從 JSON 回應檢視搜尋結果。Use this quickstart to make your first call to the Bing Video Search API and view a search result from the JSON response. 這個簡單的 JavaScript 應用程式會將 HTTP 影片搜尋查詢傳送給 API,並顯示回應。This simple JavaScript application sends an HTTP video search query to the API, and displays the response. 雖然此應用程式是以 JavaScript 撰寫,並且使用 Node.js,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in JavaScript and uses Node.js, the API is a RESTful Web service compatible with most programming languages. GitHub 上有此範例的原始程式碼,其中還有其他錯誤處理和註釋。The source code for this sample is available on GitHub with additional error handling, and code annotations.

必要條件Prerequisites

  • Node.jsNode.js

  • 適用於 JavaScript 的要求模組The Request module for JavaScript

    • 您可以使用 npm install request 來安裝此模組You can install this module using npm install request

您必須有具備 Bing 搜尋 API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Bing Search APIs. 如果您沒有 Azure 訂用帳戶,可以建立免費帳戶If you don't have an Azure subscription, you can create an account for free. 繼續之前,您需要有啟動免費試用版後所提供的存取金鑰,或是從 Azure 儀表板中取得的付費訂用帳戶金鑰。Before continuing, You will need the access key provided after activating your free trial, or a paid subscription key from your Azure dashboard.

初始化應用程式Initialize the application

  1. 在您最愛的 IDE 或編輯器中建立新的 JavaScript 檔案。Create a new JavaScript file in your favorite IDE or editor. 設定嚴謹度,並新增下列需求:Set the strictness and add the following requirement:

    'use strict';
    let https = require('https');
    
  2. 為您的 API 端點、訂用帳戶金鑰及搜尋字詞建立變數。Create variables for your API endpoint, subscription key, and your search term.

    let subscriptionKey = 'enter key here';
    let host = 'api.cognitive.microsoft.com';
    let path = '/bing/v7.0/videos/search';
    let term = 'kittens';
    

建立回應處理常式Create a response handler

  1. 建立名為 response_handler 的函式,以取得來自 API 的 JSON 回應。Create a function called response_handler to take a JSON response from the API. 建立回應本文的變數。Create a variable for the response body. 收到 data 旗標時,使用 response.on() 附加回應。Append the response when a data flag is received, using response.on().

    let response_handler = function (response) {
        let body = '';
        response.on('data', function (d) {
            body += d;
        });
    };
    
    1. end 的信號發出時,使用 response.on() 來儲存 Bing 的相關標頭 (以 bingapisx-msedge- 開頭)。When end is signaled, use response.on() to store the bing-related headers (beginning with bingapis or x-msedge-). 然後使用 JSON.parse() 剖析 JSON,接著使用 JSON.stringify() 將其轉換成字串並列印。Then parse the JSON using JSON.parse(), convert it to a string with JSON.stringify(), and print it.

      response.on('end', function () {
          for (var header in response.headers)
              // header keys are lower-cased by Node.js
              if (header.startsWith("bingapis-") || header.startsWith("x-msedge-"))
                   console.log(header + ": " + response.headers[header]);
          body = JSON.stringify(JSON.parse(body), null, '  ');
          //JSON Response body
          console.log(body);
      });
      

建立及傳送搜尋要求Create and send the search request

  1. 建立稱為 bing_video_search() 的函式。Create a function called bing_video_search(). 新增要求的參數,包括您的主機名稱和標頭。Add the parameters for your request including your host name, and headers. 編碼搜尋字詞,並以 ?q= 參數將其附加到 path 參數。Encode your search term and append it to your path parameter with the ?q= parameter. 然後以 req.end() 傳送要求。Then send the request with req.end().

    let bing_video_search = function (search_term) {
      console.log('Searching videos for: ' + term);
      let request_params = {
            method : 'GET',
            hostname : host,
            path : path + '?q=' + encodeURIComponent(search_term),
            headers : {
                'Ocp-Apim-Subscription-Key' : subscriptionKey,
            }
        };
        let req = https.request(request_params, response_handler);
        req.end();
    }
    

JSON 回應JSON response

如以下範例所示,成功的回應會以 JSON 格式來傳回:A successful response is returned in JSON, as shown in the following example:

{
    "_type": "Videos",
    "instrumentation": {},
    "readLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?q=kittens",
    "webSearchUrl": "https://www.bing.com/videos/search?q=kittens",
    "totalEstimatedMatches": 1000,
    "value": [
        {
            "webSearchUrl": "https://www.bing.com/videos/search?q=kittens&view=...",
            "name": "Top 10 cute kitten videos compilation",
            "description": "HELP HOMELESS ANIMALS AND WIN A PRIZE BY CHOOSING...",
            "thumbnailUrl": "https://tse4.mm.bing.net/th?id=OVP.n1aE_Oikl4MtzBb...",
            "datePublished": "2014-11-12T22:47:36.0000000",
            "publisher": [
                {
                    "name": "Fabrikam"
                }
            ],
            "creator": {
                "name": "Marcus Appel"
            },
            "isAccessibleForFree": true,
            "contentUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
            "hostPageUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
            "encodingFormat": "h264",
            "hostPageDisplayUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
            "width": 480,
            "height": 360,
            "duration": "PT3M52S",
            "motionThumbnailUrl": "https://tse4.mm.bing.net/th?id=OM.j4QyJAENJphdZQ_1501386166&pid=Api",
            "embedHtml": "<iframe width=\"1280\" height=\"720\" src=\"https://www.fabrikam.com/embed/8HVWitAW-Qg?autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>",
            "allowHttpsEmbed": true,
            "viewCount": 7513633,
            "thumbnail": {
                "width": 300,
                "height": 168
            },
            "videoId": "655D98260D012432848F6558260D012432848F",
            "allowMobileEmbed": true,
            "isSuperfresh": false
        },
        . . .
    ],
    "nextOffset": 36,
    "queryExpansions": [
        {
            "text": "Kittens Meowing",
            "displayText": "Meowing",
            "webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Meowing...",
            "searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
            "thumbnail": {
                "thumbnailUrl": "https://tse3.mm.bing.net/th?q=Kittens+Meowing&pid..."
            }
        },
        {
            "text": "Funny Kittens",
            "displayText": "Funny",
            "webSearchUrl": "https://www.bing.com/videos/search?q=Funny+Kittens...",
            "searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
            "thumbnail": {
                "thumbnailUrl": "https://tse3.mm.bing.net/th?q=Funny+Kittens&..."
            }
        },
        . . .
    ],
    "pivotSuggestions": [
        {
            "pivot": "kittens",
            "suggestions": [
                {
                    "text": "Cat",
                    "displayText": "Cat",
                    "webSearchUrl": "https://www.bing.com/videos/search?q=Cat...",
                    "searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
                    "thumbnail": {
                        "thumbnailUrl": "https://tse3.mm.bing.net/th?q=Cat&pid=Api..."
                    }
                },
                {
                    "text": "Feral Cat",
                    "displayText": "Feral Cat",
                    "webSearchUrl": "https://www.bing.com/videos/search?q=Feral+Cat...",
                    "searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
                    "thumbnail": {
                        "thumbnailUrl": "https://tse3.mm.bing.net/th?q=Feral+Cat&pid=Api&..."
                    }
                }
            ]
        }
    ],
    "relatedSearches": [
        {
            "text": "Kittens Being Born",
            "displayText": "Kittens Being Born",
            "webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Being+Born...",
            "searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
            "thumbnail": {
                "thumbnailUrl": "https://tse1.mm.bing.net/th?q=Kittens+Being+Born&pid=..."
            }
        },
        . . .
    ]
}

後續步驟Next steps

另請參閱See also

什麼是 Bing 影片搜尋 API?What is the Bing Video Search API?