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
你们是程序员吧,来玩点更技术的东西。比如,可以去逛逛 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