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('獲取數據錯誤')
GO TO FULL VERSION