Python API 入門
Chris Ramakers
Engineering manager


JSON

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
# 不帶標頭的 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
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 入門