Search code examples
jsonpython-3.xflaskgoogle-geocodergeocode

How to correctly access Geocode API response in python


I am using Flask and Google's geocode API to get data about a city, I want to return its coordinates as JSON. Here is the related code.

from flask import Flask, request, json
import googlemaps
from datetime import datetime
import requests

app = Flask(__name__)

gmaps = googlemaps.Client(key='My-Key') #I replaced my key

@app.route("/search/<city>", methods=['GET'])
def _find_nearby_events(city):
    request_address = '%(city)s , IN' % {'city':city}
    geocode_result = gmaps.geocode(request_address)

    coordinates = geocode_result["results"][0]["geometry"]["location"]

    return json.dumps(coordinates)

Now when I use postman to send a GET request to "http://127.0.0.1:5000/search/pune" it gives back this error in my console

  File "/home/akshay/Black_Thunder/event-listing-microservice/maps/views.py", line 51, in _find_nearby_events
coordinates = geocode_result["results"][0]["geometry"]["location"]
TypeError: list indices must be integers or slices, not str

Now I can access the required content if I change the expression of coordinates above as

coordinates = geocode_result[0]["geometry"]["location"]

I am not able to understand why is this. The JSON response which Geocode API sends can be accessed here. This response is also generated if I use the below URL through browser

https://maps.googleapis.com/maps/api/geocode/json?address=pune,+IN&key=[My-Key]

(substitute your key)

Also, I wanted to know if there is a more pythonic way to return the code.


Solution

  • As outlined in the doc:

    The return type is a list of geocoding results

    Basically, the geocode function returns only the results key in the usual response that you linked to. You can see that here: https://github.com/googlemaps/google-maps-services-python/blob/master/googlemaps/geocoding.py#L68