Brian Risk
Brian Risk

Reputation: 1449

Basics of Bing Web Search API v5.0

I'm trying to start with the basics and get any returned results from the Azure API for Bing's web search. I have successfully produced results through their sandbox API Testing Console, but in a live environment am not gettng anywhere. I am familiar with previous SO posts on the Bing API, but these responses are 4 or 5 years old and do not appear to reference the current API.

The Azure docs reference setting the Ocp-Apim-Subscription-Key header to the API key. It's frustrating when in places Microsoft's own documentation appears very dated. I am sure I am the first to complain about this!

Note: while writing up this question, I got a working solution. I am going ahead posting along with an answer with working code. Examples for the Bing API v5.0 seem few and far between.

Upvotes: 0

Views: 1333

Answers (2)

John Psaroudakis
John Psaroudakis

Reputation: 259

The API reference page (https://dev.cognitive.microsoft.com/docs/services/56b43eeccf5ff8098cef3807/operations/56b4447dcf5ff8098cef380d) includes code snippets at the bottom for most popular programming languages.

In general, you can find the reference page for each Cognitive Services API by clicking on the 'API Reference' teal button near the top of each API page.

Upvotes: 0

Brian Risk
Brian Risk

Reputation: 1449

The working code that I found will hopefully help you get started:

$accountKey = 'the_account_key';

$url =  'https://api.cognitive.microsoft.com/bing/v5.0/search?q=billgates&count=10&offset=0&mkt=en-us&safesearch=Moderate';    

// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Ocp-Apim-Subscription-Key: $accountKey"
  )
);
$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);

echo $file;

This is the raw response. You'll want to decode the JSON and work with that object:

$jsonobj = json_decode($file);

Upvotes: 2

Related Questions