クイック スタート:Bing Image Search REST API と C# を使用してイメージを検索するQuickstart: Search for images using the Bing Image Search REST API and C#
警告
Bing Search API は、Cognitive Services から Bing Search Services に移行されます。Bing Search APIs are moving from Cognitive Services to Bing Search Services. 2020 年 10 月 30 日 以降、Bing Search の新しいインスタンスは、こちらに記載されているプロセスに従ってプロビジョニングする必要があります。Starting October 30, 2020, any new instances of Bing Search need to be provisioned following the process documented here. Cognitive Services を使用してプロビジョニングされた Bing Search API は、次の 3 年間、または Enterprise Agreement の終わり (どちらか先に発生した方) までサポートされます。Bing Search APIs provisioned using Cognitive Services will be supported for the next three years or until the end of your Enterprise Agreement, whichever happens first. 移行手順については、Bing Search Services に関するページを参照してください。For migration instructions, see Bing Search Services.
このクイックスタートでは、Bing Image Search API に検索要求を送信する方法について説明します。Use this quickstart to learn how to send search requests to the Bing Image Search API. この C# アプリケーションは、検索クエリを API に送信し、その結果から最初の画像の URL を表示します。This C# application sends a search query to the API, and displays the URL of the first image in the results. このアプリケーションは C# で記述されていますが、この API はほとんどのプログラミング言語と互換性のある RESTful Web サービスです。Although this application is written in C#, 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
- Visual Studio 2017 またはそれ以降の任意のエディション。Any edition of Visual Studio 2017 or later.
- NuGet パッケージとして入手できる Json.NET フレームワーク。The Json.NET framework, available as a NuGet package.
- Linux/macOS を使用している場合、このアプリケーションは Mono を使用して実行できます。If you're using Linux/MacOS, this application can be run using Mono.
Azure リソースを作成するCreate an Azure resource
次のいずれかの Azure リソースを作成して、Bing Image Search API の使用を開始します。Start using the Bing Image Search API by creating one of the following Azure resources.
Bing Search v7 リソースBing Search v7 resource
- ご自身でリソースを削除するまでは Azure portal からご利用いただけます。Available through the Azure portal until you delete the resource.
- Free 価格レベルを使ってサービスを試用し、後から運用環境用の有料レベルにアップグレードします。Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
マルチサービス リソースMulti-service resource
- ご自身でリソースを削除するまでは Azure portal からご利用いただけます。Available through the Azure portal until you delete the resource.
- 複数の Cognitive Services 全体で同じキーとエンドポイントをアプリケーションに使用します。Use the same key and endpoint for your applications, across multiple Cognitive Services.
プロジェクトの作成と初期化Create and initialize a project
Visual Studio で、
BingSearchApisQuickStart
という新しいコンソール ソリューションを作成します。Create a new console solution namedBingSearchApisQuickStart
in Visual Studio. 次に、メイン コード ファイルに次の名前空間を追加します。Then, add the following namespaces to the main code file:using System; using System.Net; using System.IO; using System.Collections.Generic; using Newtonsoft.Json.Linq;
API エンドポイント、サブスクリプション キー、および検索用語の変数を作成します。Create variables for the API endpoint, your subscription key, and search term.
uriBase
には、次のコードのグローバル エンドポイントか、Azure portal に表示される、対象のリソースのカスタム サブドメイン エンドポイントを使用できます。ForuriBase
, you can use the global endpoint in the following code, or use the custom subdomain endpoint displayed in the Azure portal for your resource.//... namespace BingSearchApisQuickstart { class Program { // Replace the this string with your valid access key. const string subscriptionKey = "enter your key here"; const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"; const string searchTerm = "tropical ocean"; //...
Bing Image Search 応答の書式を設定する構造体を作成するCreate a struct to format the Bing Image Search response
画像の検索結果と JSON ヘッダー情報を格納する SearchResult
構造体を定義します。Define a SearchResult
struct to contain the image search results and JSON header information.
namespace BingSearchApisQuickstart
{
class Program
{
//...
struct SearchResult
{
public String jsonResult;
public Dictionary<String, String> relevantHeaders;
}
//...
検索要求を送信するメソッドを作成するCreate a method to send search requests
API に対する呼び出しを実行する BingImageSearch
という名前のメソッドを作成し、戻り値の型を前に作成した SearchResult
構造体に設定します。Create a method named BingImageSearch
to perform the call to the API, and set the return type to the SearchResult
struct created previously.
//...
namespace BingSearchApisQuickstart
{
//...
class Program
{
//...
static SearchResult BingImageSearch(string searchTerm)
{
}
//...
画像の検索要求の作成と処理Create and handle an image search request
BingImageSearch
メソッドで、次の手順を実行します。In the BingImageSearch
method, perform the following steps:
検索要求の URI を構築します。Construct the URI for the search request. 文字列に追加する前に、
SearchTerm
検索語句を書式設定します。Format theSearchTerm
search term before you append it to the string.static SearchResult BingImageSearch(string SearchTerm){ var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(SearchTerm); //...
Web 要求を送信し、応答を JSON 文字列として取得します。Send the web request and get the response as a JSON string.
WebRequest request = WebRequest.Create(uriQuery); request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey; HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result; string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
検索結果オブジェクトを作成し、Bing HTTP ヘッダーを抽出します。Create the search result object and extract the Bing HTTP headers. 次に、
searchResult
を返します。Then, returnsearchResult
.// Create the result object for return var searchResult = new SearchResult() { jsonResult = json, relevantHeaders = new Dictionary<String, String>() }; // Extract Bing HTTP headers foreach (String header in response.Headers) { if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-")) searchResult.relevantHeaders[header] = response.Headers[header]; } return searchResult;
応答の処理と表示Process and view the response
メイン メソッドで
BingImageSearch()
を呼び出し、返された応答を格納します。In the main method, callBingImageSearch()
and store the returned response. 次に、JSON をオブジェクトに逆シリアル化します。Then, deserialize the JSON into an object.SearchResult result = BingImageSearch(searchTerm); //deserialize the JSON response from the Bing Image Search API dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.jsonResult);
jsonObj
から最初に返された画像を取得し、画像のタイトルと URL を出力します。Get the first returned image fromjsonObj
, and print out the title and a URL to the image.var firstJsonObj = jsonObj["value"][0]; Console.WriteLine("Title for the first image result: " + firstJsonObj["name"]+"\n"); //After running the application, copy the output URL into a browser to see the image. Console.WriteLine("URL for the first image result: " + firstJsonObj["webSearchUrl"]+"\n");
JSON の応答例Example JSON response
Bing Image Search API からの応答は、JSON として返されます。Responses from the Bing Image Search API are returned as JSON. このサンプル応答は、1 つの結果だけを表示するように切り詰められています。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"
}]
}