Skip to content

Commit 641dfcf

Browse files
committed
Added code samples for Go, Ruby, and PHP to match what's published on docs.microsoft.com for Bing Web Search.
1 parent 5c6a3b8 commit 641dfcf

File tree

3 files changed

+205
-0
lines changed

3 files changed

+205
-0
lines changed

go/Search/BingWebSearchv7.go

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package main
2+
import (
3+
"fmt"
4+
"net/http"
5+
"io/ioutil"
6+
"time"
7+
"encoding/json"
8+
)
9+
10+
// This struct formats the answers provided by the Bing Web Search API.
11+
type BingAnswer struct {
12+
Type string `json:"_type"`
13+
QueryContext struct {
14+
OriginalQuery string `json:"originalQuery"`
15+
} `json:"queryContext"`
16+
WebPages struct {
17+
WebSearchURL string `json:"webSearchUrl"`
18+
TotalEstimatedMatches int `json:"totalEstimatedMatches"`
19+
Value []struct {
20+
ID string `json:"id"`
21+
Name string `json:"name"`
22+
URL string `json:"url"`
23+
IsFamilyFriendly bool `json:"isFamilyFriendly"`
24+
DisplayURL string `json:"displayUrl"`
25+
Snippet string `json:"snippet"`
26+
DateLastCrawled time.Time `json:"dateLastCrawled"`
27+
SearchTags []struct {
28+
Name string `json:"name"`
29+
Content string `json:"content"`
30+
} `json:"searchTags,omitempty"`
31+
About []struct {
32+
Name string `json:"name"`
33+
} `json:"about,omitempty"`
34+
} `json:"value"`
35+
} `json:"webPages"`
36+
RelatedSearches struct {
37+
ID string `json:"id"`
38+
Value []struct {
39+
Text string `json:"text"`
40+
DisplayText string `json:"displayText"`
41+
WebSearchURL string `json:"webSearchUrl"`
42+
} `json:"value"`
43+
} `json:"relatedSearches"`
44+
RankingResponse struct {
45+
Mainline struct {
46+
Items []struct {
47+
AnswerType string `json:"answerType"`
48+
ResultIndex int `json:"resultIndex"`
49+
Value struct {
50+
ID string `json:"id"`
51+
} `json:"value"`
52+
} `json:"items"`
53+
} `json:"mainline"`
54+
Sidebar struct {
55+
Items []struct {
56+
AnswerType string `json:"answerType"`
57+
Value struct {
58+
ID string `json:"id"`
59+
} `json:"value"`
60+
} `json:"items"`
61+
} `json:"sidebar"`
62+
} `json:"rankingResponse"`
63+
}
64+
65+
// Declare the main function. This is required for all Go programs.
66+
func main() {
67+
const endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/search"
68+
token := "YOUR-ACCESS-KEY"
69+
searchTerm := "Microsoft Cognitive Services"
70+
71+
// Declare a new GET request.
72+
req, err := http.NewRequest("GET", endpoint, nil)
73+
if err != nil {
74+
panic(err)
75+
}
76+
77+
// Add the payload to the request.
78+
param := req.URL.Query()
79+
param.Add("q", searchTerm)
80+
req.URL.RawQuery = param.Encode()
81+
82+
// Insert the request header.
83+
req.Header.Add("Ocp-Apim-Subscription-Key", token)
84+
85+
// Instantiate a client.
86+
client := new(http.Client)
87+
// Send the request to Bing.
88+
resp, err := client.Do(req)
89+
if err != nil {
90+
panic(err)
91+
}
92+
// Close the connection.
93+
defer resp.Body.Close()
94+
body, err := ioutil.ReadAll(resp.Body)
95+
if err != nil {
96+
panic(err)
97+
}
98+
//Create a new answer struct.
99+
ans := new(BingAnswer)
100+
err = json.Unmarshal(body, &ans)
101+
if err != nil {
102+
fmt.Println(err)
103+
}
104+
// Iterate over search results and print the result name and URL.
105+
for _, result := range ans.WebPages.Value {
106+
fmt.Println(result.Name, "||", result.URL)
107+
}
108+
109+
}

php/Search/BingWebSearchv7.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
// Replace with a valid subscription key from your Azure account.
3+
$accessKey = 'enter key here';
4+
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
5+
$term = 'Microsoft Cognitive Services';
6+
7+
function BingWebSearch ($url, $key, $query) {
8+
/*
9+
* Prepare the HTTP request.
10+
* NOTE: Use the key 'http' even if you are making an HTTPS request.
11+
* See: http://php.net/manual/en/function.stream-context-create.php.
12+
*/
13+
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
14+
$options = array ('http' => array (
15+
'header' => $headers,
16+
'method' => 'GET'));
17+
18+
// Perform the request and receive a response.
19+
$context = stream_context_create($options);
20+
$result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
21+
22+
// Extract Bing HTTP headers.
23+
$headers = array();
24+
foreach ($http_response_header as $k => $v) {
25+
$h = explode(":", $v, 2);
26+
if (isset($h[1]))
27+
if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
28+
$headers[trim($h[0])] = trim($h[1]);
29+
}
30+
31+
return array($headers, $result);
32+
}
33+
// Validate the subscription key.
34+
if (strlen($accessKey) == 32) {
35+
36+
print "Searching the Web for: " . $term . "\n";
37+
// Makes the request.
38+
list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);
39+
40+
print "\nRelevant Headers:\n\n";
41+
foreach ($headers as $k => $v) {
42+
print $k . ": " . $v . "\n";
43+
}
44+
// Prints JSON encoded response.
45+
print "\nJSON Response:\n\n";
46+
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
47+
48+
} else {
49+
50+
print("Invalid Bing Search API subscription key!\n");
51+
print("Please paste yours into the source code.\n");
52+
53+
}
54+
?>

ruby/Search/BingWebSearchv7.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
require 'net/https'
2+
require 'uri'
3+
require 'json'
4+
5+
# Replace with a valid subscription key from your Azure account.
6+
accessKey = "enter key here"
7+
uri = "https://api.cognitive.microsoft.com"
8+
path = "/bing/v7.0/search"
9+
10+
term = "Microsoft Cognitive Services"
11+
12+
# Validate the subscription key.
13+
if accessKey.length != 32 then
14+
puts "Invalid Bing Search API subscription key!"
15+
puts "Please paste yours into the source code."
16+
abort
17+
end
18+
# Construct the endpoint uri.
19+
uri = URI(uri + path + "?q=" + URI.escape(term))
20+
21+
puts "Searching the Web for: " + term
22+
23+
# Create the request.
24+
request = Net::HTTP::Get.new(uri)
25+
request['Ocp-Apim-Subscription-Key'] = accessKey
26+
27+
# Get the response.
28+
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
29+
http.request(request)
30+
end
31+
32+
puts "\nRelevant Headers:\n\n"
33+
response.each_header do |key, value|
34+
# Header names are lower-cased.
35+
if key.start_with?("bingapis-") or key.start_with?("x-msedge-") then
36+
puts key + ": " + value
37+
end
38+
end
39+
40+
# Print the response.
41+
puts "\nJSON Response:\n\n"
42+
puts JSON::pretty_generate(JSON(response.body))

0 commit comments

Comments
 (0)