構造化データの扱い方

Pythonを使ったAPI入門

Chris Ramakers

Engineering manager

複雑なデータ構造

Lyric APIレスポンス

Lyric API response with HTTP 200 OK. Headers: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. Body: lyrics from "Problem Child" by AC/DC.

Album APIレスポンス

Album API response with HTTP 200 OK. Headers specify JSON content. The body includes album details for "Back in Black" by AC/DC, listing track titles.

Pythonを使ったAPI入門

複雑なデータ構造: * JSON

  • JSON
    • JavaScript Object Notation(JavaScriptオブジェクト表記法)
    • 広くサポートされている
    • 人が読みやすく、機械でも利用できる
  • コンテンツタイプ、MIMEタイプ、またはメディアタイプ
  • その他の形式
    • XML
    • CSV
    • YAML

Album APIレスポンス

Album API response with HTTP 200 OK. Headers specify JSON content. The body includes album details for "Back in Black" by AC/DC, listing track titles.

Pythonを使ったAPI入門

PythonからJSONへ、そしてPythonに戻す

A visual representation of encoding and decoding JSON formatted text using Python. The JSON contains album details for "Back in Black" by AC/DC.

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入門

練習しましょう!

Pythonを使ったAPI入門

Preparing Video For Download...