API 请求的基本结构

Python 中的 API 入门

Chris Ramakers

Engineering Manager

什么是 URL?

  • URL = 统一资源定位符(Uniform Resource Locator)
  • 指向 API 资源的结构化地址
  • 通过自定义 URL 访问特定 API 资源
http://350.5th-ave.com/unit/243
Python 中的 API 入门

解析 URL

一个图示展示 URL 的各部分:协议(http://)、域名(350.5th-ave.com)、端口(:80)、路径(/unit/243)、查询(?floor=77)。

  • Protocol(协议) = 传输方式
  • Domain(域名) = 办公楼的街道地址
  • Port(端口) = 进入时使用的门
  • Path(路径) = 楼内具体办公室
  • Query(查询) = 其他附加指令
Python 中的 API 入门

用 requests 添加查询参数

# 将查询参数直接拼接到 URL 字符串
response = requests.get('http://350.5th-ave.com/unit/243?floor=77&elevator=True')
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
  • 使用 params 参数添加查询参数
# 创建字典
query_params = {'floor': 77, 'elevator': True}
# 通过 `params` 参数传入字典
response = requests.get('http://350.5th-ave.com/unit/243', params=query_params)
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
Python 中的 API 入门

HTTP 动词

  • 目的地:350 5th Ave 办公楼 243 室
  • URL:http://350.5th-ave.com/unit/243

动作

Verb Action Description
GET Read 查看邮箱内容
POST Create 投递新包裹到邮箱
PUT Update 用新包裹替换所有包裹
DELETE Delete 清空邮箱中的包裹
1 HTTP 动词共有 9 个,但对简单的 REST API 来说,这 4 个最常用。
Python 中的 API 入门

通过 POST 和 PUT 发送数据

# GET = 获取资源
response = requests.get('http://350.5th-ave.com/unit/243')

# POST = 创建资源 response = requests.post('http://350.5th-ave.com/unit/243', data={"key": "value"}) # PUT = 更新现有资源 response = requests.put('http://350.5th-ave.com/unit/243', data={"key": "value"})
# DELETE = 删除资源 response = requests.delete('http://350.5th-ave.com/unit/243')
  • 每个动词在 requests 包中都有对应方法
  • 使用 data 参数向 POST 或 PUT 请求传递数据。
Python 中的 API 入门

Passons à la pratique !

Python 中的 API 入门

Preparing Video For Download...