使用 Python 向 Google Maps Places API(新)发出发布请求

问题描述 投票:0回答:1

我正在尝试从谷歌地图的谷歌“新”地点 API 中检索数据,特别是新的附近搜索 API。我有一个可用的 API 密钥(它适用于旧的 Places API,我不认为我需要一个新的)我正在尝试 JSON Post 请求,因为显然大多数新 API 只接受 JSON Post 请求,而不再接受网址请求。我在网络上找到了几个使用 Python 发出 Post 请求的好例子,但其中零个是访问 Google Maps API 的。下面是我的代码示例。我相信它正在到达 API 服务器,但返回 400 代码(如下)。

[调试] [启动新的 HTTPS 连接 (1)]places.googleapis.com:443 [调试] [https]//places.googleapis.com:443“POST /v1/places:searchNearby HTTP/1.1”400 无

我尝试了此代码的几种变体,包括直接插入我的 API 密钥而不是使用变量。

from kivymd.app import MDApp

import requests
import json



class MyApp(MDApp):
    api_file = open("Maps_API.txt", "r")
    API_KEY = api_file.read()
    api_file.close()

       
    url = "https://places.googleapis.com/v1/places:searchNearby"
    data = {"includedTypes": ["gas_station"],"maxResultCount": 10,
            "locationRestriction": {
                "circle": {
                    "center": {
                        "latitude": 31.06114,
                        "longitude": -98.17896},
                    "radius": 500.0}}}
    
    
    headers = {"Content-Type": "application/json","X-Goog-Api-Key": API_KEY,"X-Goog-FieldMask": "id,displayName,location"}


    json_data = json.dumps(data)
    response = requests.post(url, data=json_data, headers=headers)
        

    print(response)
    if response.status_code == 200:
        data = response.json()
        print(data)
            
    
MyApp().run()
python json post google-places-api http-status-code-400
1个回答
0
投票

找到答案了! 如何在Python中通过Google Places API(新)文本搜索(仅ID)调用?

归结为字段掩码格式错误。需要“places.id,places.displayName,places.location”而不仅仅是“id,displayName,location”

© www.soinside.com 2019 - 2024. All rights reserved.