處理結構化資料

Python API 入門

Chris Ramakers

Engineering manager

複合資料結構

歌詞 API 回應

Lyric API 回應,HTTP 200 OK。標頭:Content-Type: plain/text、Content-Language: en-US、Last-Modified: Wed, 21 Oct 2023。內文:AC/DC 的「Problem Child」歌詞。

專輯 API 回應

Album API 回應,HTTP 200 OK。標頭指定 JSON 內容。內文為 AC/DC 的「Back in Black」專輯資訊與曲目列表。

Python API 入門

複合資料結構:JSON

  • JSON
    • JavaScript 物件標記法
    • 廣泛支援
    • 人可讀、機器可用
  • Content-type、mime-type 或 media-type
  • 其他格式
    • XML
    • CSV
    • YAML

專輯 API 回應

Album 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 請求
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
# 帶 accept 標頭的 GET 請求
response = requests.get('http://api.music-catalog.com/lyrics', headers={'accept': 'application/json'})

# 列印 JSON 文字
print(response.text)

# 解碼為 Python 物件 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"}

# 透過 `json` 參數加入播放清單 
response = requests.post("http://api.music-catalog.com/playlists", json=playlist)
# 取得 request 物件
request = response.request

# 列印 request 的 content-type 標頭
print(request.headers['content-type'])
application/json
Python API 入門

一起來練習吧!

Python API 入門

Preparing Video For Download...