处理结构化数据

Python 中的 API 入门

Chris Ramakers

Engineering manager

复杂数据结构

歌词 API 响应

歌词 API 响应,HTTP 200 OK。标头:Content-Type: plain/text,Content-Language: en-US,Last-Modified: Wed, 21 Oct 2023。正文:AC/DC《Problem Child》的歌词。

专辑 API 响应

专辑 API 响应,HTTP 200 OK。标头指明 JSON 内容。正文包含 AC/DC《Back in Black》的专辑详情与曲目列表。

Python 中的 API 入门

复杂数据结构:JSON

  • JSON
    • JavaScript 对象表示法
    • 广泛支持
    • 人可读、机可用
  • Content-Type、MIME 类型或媒体类型
  • 其他格式
    • XML
    • CSV
    • YAML

专辑 API 响应

专辑 API 响应,HTTP 200 OK。标头指明 JSON 内容。正文包含 AC/DC《Back in Black》的专辑详情与曲目列表。

Python 中的 API 入门

在 Python 与 JSON 之间转换

  使用 Python 对 JSON 文本进行编码与解码的示意图。JSON 含有 AC/DC《Back in Black》的专辑信息。

import json
album =  {'id': 42, 'title':"Back in Black"}
string = json.dumps(album) # Encodes a python object to a JSON string
album = json.loads(string) # Decodes a JSON string to a Python object
Python 中的 API 入门

请求 JSON 数据

# GET request without headers
response = requests.get('http://api.music-catalog.com/lyrics')
print(response.text)
N' I never miss Cause I'm a problem child - AC/DC, Problem Child
# GET request with an accept header
response = requests.get('http://api.music-catalog.com/lyrics', headers={'accept': 'application/json'})

# Print the JSON text
print(response.text)

# Decode into a Python object data = response.json() print(data['artist'])
{'artist': 'AC/DC', 'lyric': "N' I never miss Cause I'm a problem child", 'track': 'Problem Child'}

AC/DC
Python 中的 API 入门

发送 JSON 数据

import requests
playlist = {"name": "Road trip", "genre":"rock", "private":"true"}

# Add the playlist using via the `json` argument 
response = requests.post("http://api.music-catalog.com/playlists", json=playlist)
# Get the request object
request = response.request

# Print the request content-type header
print(request.headers['content-type'])
application/json
Python 中的 API 入门

Passons à la pratique !

Python 中的 API 入门

Preparing Video For Download...