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

使用本快速入門,開始將搜尋要求傳送至 Bing 影像搜尋 API。Use this quickstart to start sending search requests to the Bing Image Search API. 這個 JavaScript 應用程式會將搜尋查詢傳送至 API,並顯示結果中第一個影像的 URL。This JavaScript application sends a search query to the API, and displays the URL of the first image in the results. 雖然此應用程式是以 JavaScript 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in Javascript, 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 annotations.

必要條件Prerequisites

另請參閱認知服務定價 - Bing 搜尋 APISee also Cognitive Services Pricing - Bing Search API.

建立應用程式並將其初始化Create and initialize the application

  1. 在您最愛的 IDE 或編輯器中建立新的 JavaScript 檔案,並設定嚴謹度 和 https 需求。Create a new JavaScript file in your favorite IDE or editor, and set the strictness and https requirements.

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

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

建構搜尋要求和查詢。Construct the search request and query.

  1. 使用上一個步驟中的變數來製作適用於 API 要求的搜尋 URL 格式。Use the variables from the last step to format a search URL for the API request. 您的搜尋字詞必須先進行 URL 編碼,再傳送至 API。Your search term must be URL-encoded before being sent to the API.

    let request_params = {
        method : 'GET',
        hostname : host,
        path : path + '?q=' + encodeURIComponent(search),
        headers : {
        'Ocp-Apim-Subscription-Key' : subscriptionKey,
        }
    };
    
  2. 使用要求程式庫將查詢傳送給 API。Use the request library to send your query to the API. 下一節中將會定義 response_handlerresponse_handler will be defined in the next section.

    let req = https.request(request_params, response_handler);
    req.end();
    

處理及剖析回應Handle and parse the response

  1. 定義一個名為 response_handler 的函式,此函式會接受 HTTP 呼叫 response 作為參數。define a function named response_handler that takes an HTTP call, response, as a parameter. 在此函式內執行下列步驟:Do the following steps within this function:

    1. 定義一個變數來包含 JSON 回應本文。Define a variable to contain the body of the JSON response.

      let response_handler = function (response) {
          let body = '';
      };
      
    2. 當呼叫 data 旗標時,儲存回應本文Store the body of the response when the data flag is called

      response.on('data', function (d) {
          body += d;
      });
      
    3. 如果顯示了 end 旗標,請取得 JSON 回應中的第一個結果。When an end flag is signaled, get the first result from the JSON response. 列印第一個影像的 URL,以及傳回的影像總數。Print the URL for the first image, along with the total number of returned images.

      response.on('end', function () {
          let firstImageResult = imageResults.value[0];
          console.log(`Image result count: ${imageResults.value.length}`);
          console.log(`First image thumbnail url: ${firstImageResult.thumbnailUrl}`);
          console.log(`First image web search url: ${firstImageResult.webSearchUrl}`);
       });
      

範例 JSON 回應Example JSON response

來自「Bing 影像搜尋 API」的回應會以 JSON 形式傳回。Responses from the Bing Image Search API are returned as JSON. 本範例回應已截斷而只顯示單一結果。This sample response has been truncated to show a single result.

{
"_type":"Images",
"instrumentation":{
    "_type":"ResponseInstrumentation"
},
"readLink":"images\/search?q=tropical ocean",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=tropical ocean&FORM=OIIARP",
"totalEstimatedMatches":842,
"nextOffset":47,
"value":[
    {
        "webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=tropical+ocean&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&simid=608027248313960152",
        "name":"My Life in the Ocean | The greatest WordPress.com site in ...",
        "thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.fmwSKKmKpmZtJiBDps1kLAHaEo&pid=Api",
        "datePublished":"2017-11-03T08:51:00.0000000Z",
        "contentUrl":"https:\/\/mylifeintheocean.files.wordpress.com\/2012\/11\/tropical-ocean-wallpaper-1920x12003.jpg",
        "hostPageUrl":"https:\/\/mylifeintheocean.wordpress.com\/",
        "contentSize":"897388 B",
        "encodingFormat":"jpeg",
        "hostPageDisplayUrl":"https:\/\/mylifeintheocean.wordpress.com",
        "width":1920,
        "height":1200,
        "thumbnail":{
        "width":474,
        "height":296
        },
        "imageInsightsToken":"ccid_fmwSKKmK*mid_8607ACDACB243BDEA7E1EF78127DA931E680E3A5*simid_608027248313960152*thid_OIP.fmwSKKmKpmZtJiBDps1kLAHaEo",
        "insightsMetadata":{
        "recipeSourcesCount":0,
        "bestRepresentativeQuery":{
            "text":"Tropical Beaches Desktop Wallpaper",
            "displayText":"Tropical Beaches Desktop Wallpaper",
            "webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Tropical+Beaches+Desktop+Wallpaper&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&FORM=IDBQDM"
        },
        "pagesIncludingCount":115,
        "availableSizesCount":44
        },
        "imageId":"8607ACDACB243BDEA7E1EF78127DA931E680E3A5",
        "accentColor":"0050B2"
    }]
}

後續步驟Next steps

另請參閱See also