使用python-google-places API统计城市餐厅时遇INVALID_REQUEST错误的原因排查
Hey there! Let's dig into why you're hitting that INVALID_REQUEST error when trying to count restaurants in your city using the python-google-places library. This error typically signals that the Google Places API can't parse or process your request correctly, so here are the most common causes to check:
Common Causes & Fixes
Missing or misconfigured required parameters
The Places API needs specific parameters to function properly for restaurant searches:- A valid
location(must be a latitude/longitude pair like(37.7749, -122.4194)— passing just a city name directly might fail unless you first convert it to coordinates via geocoding) - A
radiusvalue between 1 and 50000 meters (values outside this range will trigger an invalid request) - A correctly spelled
typeparameter (use'restaurant'or'food'— watch for typos like'resturant')
Also, avoid conflicting parameters: you can't useradiusalongsiderankby=distancein the same request.
- A valid
Invalid or improperly set up API key
This is one of the most frequent culprits:- Double-check that your API key is copied correctly (no extra spaces or typos)
- Verify the Places API is enabled in your Google Cloud Console project
- Confirm billing is enabled for your project (Google requires billing setup even for free-tier usage)
- Check if your key has restrictions (like IP or HTTP referrer limits) that block your local development requests
Incorrect parameter formatting
The python-google-places library expects parameters in specific formats:- Numeric values like
radiusmust be integers, not strings - Ensure you're using the library's expected syntax for parameters (e.g.,
typesvsquery— refer to the library's docs for exact usage) - Avoid passing extra, unrecognized parameters that the API doesn't understand
- Numeric values like
Failed geocoding of your city name
If you're using a city name instead of coordinates, the library or API might not resolve it correctly. Try manually geocoding your city via the Google Geocoding API first to get precise coordinates, then use those in yourlocationparameter.Quotas or rate limiting (less likely, but worth checking)
While this usually returnsOVER_QUERY_LIMIT, hitting your API quota or sending requests too quickly might occasionally manifest as an invalid request. Head to your Google Cloud Console's quota page to confirm you haven't exhausted your limits.
Quick Debug Tip
Start with a minimal, hardcoded request to isolate the issue. For example:
from googleplaces import GooglePlaces API_KEY = "your_valid_key_here" google_places = GooglePlaces(API_KEY) # Test with a known location and radius query_result = google_places.nearby_search( location=(37.7749, -122.4194), radius=5000, types=['restaurant'] ) print(query_result.status)
If this works, you know the issue is with your original parameters or city name handling.
内容的提问来源于stack exchange,提问作者Saulo Souza

