快速入門:使用 Bing 影像搜尋 REST API 和 Node.js 來搜尋影像

警告

2020 年 10 月 30 日,Bing 搜尋 API 已從 Azure AI 服務移至Bing 搜尋服務。 本文件僅供參考之用。 如需更新的文件,請參閱 Bing 搜尋 API 文件。 如需針對 Bing 搜尋建立新 Azure 資源的指示,請參閱透過 Azure Marketplace 建立 Bing 搜尋資源

使用本快速入門,了解如何將搜尋要求傳送至 Bing 影像搜尋 API。 這個 JavaScript 應用程式會將搜尋查詢傳送至 API,並顯示結果中第一個影像的 URL。 雖然此應用程式是以 JavaScript 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。

必要條件

如需詳細資訊,請參閱Azure AI 服務定價 - Bing 搜尋 API

建立應用程式並將其初始化

  1. 在您慣用的 IDE 或編輯器中建立新的 JavaScript 檔案,並設定嚴謹度和 HTTPS 需求。

    'use strict';
    let https = require('https');
    
  2. 建立適用於 API 端點、影像 API 搜尋路徑、您訂用帳戶金鑰及搜尋字詞的變數。 針對 host,您可以使用下列程式碼中的全域端點,或使用 Azure 入口網站中針對您的資源顯示的自訂子網域端點。

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

建構搜尋要求和查詢。

  1. 使用上一個步驟中的變數來製作適用於 API 要求的搜尋 URL 格式。 先將搜尋字詞進行 URL 編碼,再將其傳送至 API。

    let request_params = {
        method : 'GET',
        hostname : host,
        path : path + '?q=' + encodeURIComponent(search),
        headers : {
        'Ocp-Apim-Subscription-Key' : subscriptionKey,
        }
    };
    
  2. 使用要求程式庫將查詢傳送給 API。

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

處理及剖析回應

  1. 定義一個名為 response_handler 的函式,此函式會接受 HTTP 呼叫 response 作為參數。

  2. 在此函式中,定義一個變數來包含 JSON 回應本文。

    let response_handler = function (response) {
        let body = '';
    };
    
  3. 在呼叫 data 旗標時,儲存回應本文。

    response.on('data', function (d) {
        body += d;
    });
    
  4. 如果顯示了 end 旗標,請取得 JSON 回應中的第一個結果。 列印第一個影像的 URL,以及傳回的影像總數。

    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 回應

來自「Bing 影像搜尋 API」的回應會以 JSON 形式傳回。 本範例回應已截斷而只顯示單一結果。

{
"_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"
    }]
}

後續步驟

另請參閱