快速入门:使用 Python 向必应实体搜索 REST API 发送搜索请求

警告

2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源

参考本快速入门对必应实体搜索 API 进行第一次调用并查看 JSON 响应。 这个简单的 Python 应用程序会向该 API 发送一个新闻搜索查询并显示响应。 该示例的源代码可在 GitHub 上获得。

虽然此应用程序是使用 Python 编写的,但 API 是一种 RESTful Web 服务,与大多数编程语言兼容。

先决条件

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应实体搜索 API。

必应实体搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 v7 资源的付费层中提供。

多服务资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。

创建并初始化应用程序

  1. 在你喜欢使用的 IDE 或编辑器中创建一个新的 Python 文件,然后添加以下 import 语句。 为你的订阅密钥、终结点、市场和搜索查询创建变量。 你可以使用以下代码中的全局终结点,或者使用资源的 Azure 门户中显示的自定义子域终结点。

    import http.client, urllib.parse
    import json
    
    subscriptionKey = 'ENTER YOUR KEY HERE'
    host = 'api.bing.microsoft.com'
    path = '/v7.0/search'
    mkt = 'en-US'
    query = 'italian restaurants near me'
    
  2. 通过将市场变量追加到 ?mkt= 参数来创建请求 URL。 对查询进行 URL 编码并将其追加到 &q= 参数。

    params = '?mkt=' + mkt + '&q=' + urllib.parse.quote (query)
    

发送请求并获取响应

  1. 创建一个名为 get_suggestions() 的函数。

  2. 在此函数中,将你的订阅密钥添加到一个字典中,使用 Ocp-Apim-Subscription-Key 作为键。

  3. 使用 http.client.HTTPSConnection() 创建一个 HTTPS 客户端对象。 使用 request() 以及你的路径、参数和标头信息发送 GET 请求。

  4. 通过 getresponse() 存储响应,并返回 response.read()

    def get_suggestions ():
     headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
     conn = http.client.HTTPSConnection (host)
     conn.request ("GET", path + params, None, headers)
     response = conn.getresponse ()
     return response.read()
    
  5. 调用 get_suggestions() 并输出 JSON 响应。

    result = get_suggestions ()
    print (json.dumps(json.loads(result), indent=4))
    

示例 JSON 响应

在 JSON 中返回成功的响应,如以下示例所示:

{
  "_type": "SearchResponse",
  "queryContext": {
    "originalQuery": "italian restaurant near me",
    "askUserForLocation": true
  },
  "places": {
    "value": [
      {
        "_type": "LocalBusiness",
        "webSearchUrl": "https://www.bing.com/search?q=sinful+bakery&filters=local...",
        "name": "Liberty's Delightful Sinful Bakery & Cafe",
        "url": "https://www.contoso.com/",
        "entityPresentationInfo": {
          "entityScenario": "ListItem",
          "entityTypeHints": [
            "Place",
            "LocalBusiness"
          ]
        },
        "address": {
          "addressLocality": "Seattle",
          "addressRegion": "WA",
          "postalCode": "98112",
          "addressCountry": "US",
          "neighborhood": "Madison Park"
        },
        "telephone": "(800) 555-1212"
      },

      . . .
      {
        "_type": "Restaurant",
        "webSearchUrl": "https://www.bing.com/search?q=Pickles+and+Preserves...",
        "name": "Munson's Pickles and Preserves Farm",
        "url": "https://www.princi.com/",
        "entityPresentationInfo": {
          "entityScenario": "ListItem",
          "entityTypeHints": [
            "Place",
            "LocalBusiness",
            "Restaurant"
          ]
        },
        "address": {
          "addressLocality": "Seattle",
          "addressRegion": "WA",
          "postalCode": "98101",
          "addressCountry": "US",
          "neighborhood": "Capitol Hill"
        },
        "telephone": "(800) 555-1212"
      },
      
      . . .
    ]
  }
}

后续步骤