CodeGym /Javaコース /Python SELF JA /公開APIの利用

公開APIの利用

Python SELF JA
レベル 24 , レッスン 3
使用可能

9.1 Google Maps APIの利用

人気のあるサービスの公開APIをちょっと使ってみよう。

例えば、Google Maps APIはジオコーディング、ルート取得、位置情報などのサービスを提供してるよ。 Google Maps APIを使うには、APIキーの登録が必要だよ。

ジオコーディング (住所から座標を取得する)


import requests
API_KEY = 'YOUR_GOOGLE_MAPS_API_KEY'
address = '1600 Amphitheatre Parkway, Mountain View, CA'
url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={API_KEY}'
response = requests.get(url)
data = response.json()
if data['status'] == 'OK':
    location = data['results'][0]['geometry']['location']
    lat = location['lat']
    lng = location['lng']
    print(f'座標: {lat}, {lng}')
else:
    print('ジオコーディングエラー')

9.2 OpenWeatherMap APIの利用

世界中のどんな場所でも天気情報を取得できるよ。

OpenWeatherMap APIは世界中の天気データを提供してる。APIを使うには、登録してAPIキーを手に入れなきゃね。

現在の天気の取得


import requests
API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'
city = 'London'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    weather = data['weather'][0]['description']
    temp = data['main']['temp']
    print(f'{city}の天気: {weather}, 気温: {temp}°C')
else:
    print('天気データ取得エラー')

9.3 GitHub APIの利用

プログラマーだから、もっとITっぽいことしよう。例えば、GitHubのリポジトリを探検してみるのもいいね。

GitHub APIはリポジトリ、ユーザー、団体の情報にアクセスできるよ。

リポジトリの情報取得


import requests
repo_owner = 'octocat'
repo_name = 'Hello-World'
url = f'https://api.github.com/repos/{repo_owner}/{repo_name}'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    print(f"リポジトリ: {data['name']}")
    print(f"説明: {data['description']}")
    print(f"スター数: {data['stargazers_count']}")
else:
    print('リポジトリ情報取得エラー')

9.4 YouTube Data APIの利用

YouTube Data APIは動画、チャンネル、プレイリストの情報を取得できる。APIを使うには、APIキーを手に入れなきゃね。


import requests
API_KEY = 'YOUR_YOUTUBE_API_KEY'
video_id = 'Ks-_Mh1QhMc'
url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={API_KEY}&part=snippet,contentDetails,statistics'
response = requests.get(url)
data = response.json()
if 'items' in data and len(data['items']) > 0:
    video_info = data['items'][0]
    title = video_info['snippet']['title']
    views = video_info['statistics']['viewCount']
    print(f'動画タイトル: {title}')
    print(f'再生回数: {views}')
else:
    print('動画情報取得エラー')

Open Notify APIは、国際宇宙ステーション(ISS)の現在の位置情報を提供しているよ。

ISSの現在の位置取得


import requests
url = 'http://api.open-notify.org/iss-now.json'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    position = data['iss_position']
    print(f"ISSの位置: 経度 {position['longitude']}, 緯度 {position['latitude']}")
else:
    print('データ取得エラー')
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION