最后总结

Python 中的 API 入门

Chris Ramakers

Engineering Manager

API 基础

  • API 的作用
  • API 的类型
  • URL 组成部分
  • 请求与响应结构
  • HTTP 动词

Python 中的 API 入门

用 Python 调用 API

Requests 包

import requests

HTTP 方法

# 读取资源
requests.get('https://api.my-music.com')
# 创建资源
requests.post('https://api.my-music.com', data={...})
# 更新资源
requests.put('https://api.my-music.com', data={...})
# 删除资源
requests.delete('https://api.my-music.com')

URL 参数

query_params = {'artist': 'Deep Purple'}
requests.get('http://api.my-music.com', params=query_params)

Headers

headers = {'accept': 'application/json'}
response = requests.get('http://api.my-music.com', headers=headers)
print(response.headers.get('content-type'))

状态码

response = requests.get('http://api.my-music.com')
print(response.status_code)
Python 中的 API 入门

进阶主题

  • 认证
    • 基本认证(Basic Authentication)
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API 密钥/令牌认证
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • 结构化数据
    • 请求 JSON 格式数据
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • 发送 JSON 格式数据
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Python 中的 API 入门

错误处理

  • 错误类型
    • 连接错误
    • HTTP 错误
      • 4XX 客户端错误
      • 5XX 服务器错误
  • 用状态码处理错误
    • response.status_code
  • 用异常处理错误
    • raise_for_error()
import requests
from requests.exceptions import ConnectionError, HTTPError

try:
    response = requests.get("http://api.music-catalog.com/albums") 
    response.raise_for_status()

except ConnectionError as conn_err: 
    print(f'Connection Error! {conn_err}.')

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
Python 中的 API 入门

恭喜您!

Python 中的 API 入门

Preparing Video For Download...