0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Text Search APIをPythonから利用する

Posted at

はじめに

前回の記事(Google Maps Text Search APIの使い方解説)では、
APIの基本的な使い方やリクエスト例、パラメータについて書きました。
今回はそれを踏まえ、PythonでのAPI活用例を紹介します

コード

import requests

API_KEY = 'YOUR_API_KEY'

url = 'https://places.googleapis.com/v1/places:searchText'
headers = {
    'Content-Type': 'application/json',
    'X-Goog-Api-Key': API_KEY,
    'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,places.location,places.websiteUri'
}
data = {
    'textQuery': '東京駅 ラーメン',
    'languageCode': 'ja',
    'pageSize': 20
}

response = requests.post(url, headers=headers, json=data)
results = response.json().get('places', [])
print(results)

結果

1f96d137d49ae703ab9a.png

件数が多い場合(ページング

Text Search APIのレスポンスに nextPageToken が含まれている場合、
それを使って追加の検索結果を取得します

import requests
import time

API_KEY = 'YOUR_API_KEY'

url = 'https://places.googleapis.com/v1/places:searchText'
headers = {
    'Content-Type': 'application/json',
    'X-Goog-Api-Key': API_KEY,
    'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,nextPageToken'
}
data = {
    'textQuery': '東京駅 ラーメン',
    'languageCode': 'ja',
    'pageSize': 5
}


all_places = []
while True:
    response = requests.post(url, headers=headers, json=data)
    result = response.json()
    all_places.extend(result.get('places', []))
    token = result.get('nextPageToken')
    if not token:
        break
    data['pageToken'] = token
    time.sleep(2)  # トークンが有効になるまで待つ
  • フィールドマスクの必須設定
    nextPageToken を取得するには、X-Goog-FieldMask ヘッダーに明示的な指定が必要です

注意点

  • nextPageToken がレスポンスに含まれていない場合、それ以上のデータはありません
  • 最大取得件数は 合計60件 まで
  • nextPageToken を使う際、トークン発行から有効化まで短い遅延がある場合がある
    1~2秒待ってから再リクエストすると回避できます
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?