Python: how to check whether Google street view API returns no image or the API key is expired?
<p>I want to use <a href="https://developers.google.com/maps/documentation/streetview/" rel="nofollow">Google Street View API</a> to download some images in python.</p>

<p>Sometimes there is no image return in one area, but the API key can be <strong>used</strong>. </p>

<p><a href="http://i.stack.imgur.com/pXSWd.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/pXSWd.jpg" alt="enter image description here"></a></p>

<p>Other time API key is <strong>expired</strong> or <strong>invalid</strong>, and also cannot return image. </p>

<pre><code>The Google Maps API server rejected your request. The provided API key is expired.
</code></pre>

<p>How to distinguish these two situations with code in Python?</p>

<p>Thank you very much.</p>

<p>One way to do this would be to make an api call with the <code>requests</code> library, and parse the JSON response:</p>

<pre><code>import requests
url = 'https://maps.googleapis.com/maps/api/streetview?size=600x300&amp;location=46.414382,10.013988&amp;heading=151.78&amp;pitch=-0.76&amp;key=YOUR_API_KEY'

r = requests.get(url)
results = r.json()
error_message = results.get('error_message')
</code></pre>

<p>Now <code>error_message</code> will be the text of the error message (e.g., <code>'The provided API key is expired.'</code>), or will be <code>None</code> if there is no error message. So later in your code you can check if there is an error message, and do things based on the content of the message:</p>

<pre><code>if error_message and 'The provided API key is invalid.' in error_message:
    do_something()
elif ...:
    do_something_else()
</code></pre>

<p>You could also check the key <code>'status'</code> if you just want to see if the request was successful or not:</p>

<pre><code>status = results.get('status')
</code></pre>

python api google-maps google-maps-api-3 google-street-view