Search code examples
pythongoogle-places-api

How to call via Google places API(New) Text Search (ID Only) in python?


According to documentation here if I ask, just for place_id, the call should be for free. I tried various versions of call, but all of them either did not work or gave me not just id, but also other basic info such as address, location, rating, etc. Bard told me that it is ok and as I asked just for id, the calls will really cost nothing. However it is not possible to see cost of each call and based on whole day billing I am afraid I paid also for these calls.

Should this be really free and even though address, location, etc. should be priced as basic info, it is actually given for free or should I change sth in my code?

My code:

def find_place(query, api_key):
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
    params = {
    "query": query,
    "inputtype": "textquery",
    "fieldMask": "place_id",  # Only retrieve the place ID
    "key": api_key  # Include API key
    }
    response = requests.get(base_url, params=params)
    return response.json()

Solution

  • Finally I found out how to do that properly. Now the response is only the needed field(s):

    def find_place(query, api_key):    
        # Define the API endpoint
        url = 'https://places.googleapis.com/v1/places:searchText'
    
        # Define the headers
        headers = {
            'Content-Type': 'application/json',
            'X-Goog-Api-Key': api_key,  # Replace 'API_KEY' with your actual Google Places API key
            'X-Goog-FieldMask': 'places.id'
        }
    
        # Define the data payload for the POST request
        data = {
            'textQuery': query
        }
    
        # Make the POST request
        response = requests.post(url, headers=headers, json=data)
    
        # Check if the request was successful
        if response.status_code == 200:
            # Process the response
            print(response.json())
        else:
            print(f"Error: {response.status_code}, {response.text}")
        return json.loads(response.text)