4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ZENRINMapsAPI OAuth2.0でデータ取得してみる Python

Last updated at Posted at 2025-03-12

はじめに

この記事は ZENRIN Maps APIからOAuth認証を使用して地図情報を検索したい人のための記事です

前回の続きで、
今回はPythonでAPIからデータを取得してみます

ZENRIN Maps API
無料トライアルページ
2ヶ月間無料で利用できます

環境

terminal
~ % python -V
Python 3.11.9

前回同様にウェブコンソールから以下をメモっておきます

  • APIキー
  • client_id
  • client_secret

OAuth2.0の有効化

データ取得

今回は 施設検索 を試してみます

早速、

sample.py
# coding=utf-8
import json
import requests
import urllib
import base64

## token取得
def get_token():
    url = "https://test-auth.zmaps-api.com/oauth2/token"

    client_id = '自分のclient_id'
    client_secret = '自分のclient_secret'
    # client_idとclient_secretをコロン(:)で連結してbese64エンコード
    auth = base64.b64encode(f'{client_id}:{client_secret}'.encode()).decode()

    # 認証情報をクエストヘッダに設定
    headers = {
            'Authorization' : f'Basic {auth}',
            'Content-Type' : 'application/x-www-form-urlencoded'
    }
    # 送信パラメータ
    params = urllib.parse.urlencode({'grant_type': 'client_credentials'})
    # リクエスト
    res = requests.post(url=url, data=params, headers=headers)

    if res.status_code == 200:
        d = json.loads(res.text)
        return d['access_token']

## 施設検索
def search_poi(token, parameters={}):
    # 施設検索のリクエスト先URL
    url = "https://test-web.zmaps-api.com/search/poi"
    
    # 認証情報をクエストヘッダに設定
    headers = {
            'x-api-key': '自分のAPIキー',
            'Authorization': f'Bearer {token}', # 取得したtoken
            'Content-Type' : 'application/x-www-form-urlencoded'
    }
    params = {
            'genre_pattern': '101' # 必須項目:ジャンルパターン
    }
    # 送信パラメータ ※必須項目と任意項目をマージ
    params = urllib.parse.urlencode({**params, **parameters})
    # リクエスト
    res = requests.post(url=url, data=params, headers=headers)

    if res.status_code == 200:
        return res.text


## token取得
token = get_token()
## 東京駅周辺100mにあるコンビニを検索
print(search_poi(token, {'genre_code': '00140:0014000180', 'proximity': '139.767132,35.681406,100'}))

client_id、client_secretなどは環境変数に設定しましょう

実行するとデータを取得することができました
5件ヒットしています
a4c8abc6b79e2163efc7-1.png

見やすいようにjqコマンドを使っています

まとめ

  • 流れは、まずtokenを取得して、そのtokenを使ってAPI検索
  • token取得時
    • client_idとclient_secretをコロン(:)で文字列連結してBase64エンコード
  • API検索時
    • 認証情報は、APIキー(x-api-key)と"Bearer [取得したtoken]"(Authorization)
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?