구조화된 데이터 다루기

Python으로 배우는 API 입문

Chris Ramakers

Engineering manager

복잡한 데이터 구조

가사 API 응답

HTTP 200 OK 상태의 가사 API 응답. 헤더: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. 본문: AC/DC의 "Problem Child" 가사.

앨범 API 응답

HTTP 200 OK 상태의 앨범 API 응답. 헤더에 JSON 콘텐츠 타입이 명시되어 있으며, 본문에는 AC/DC의 "Back in Black" 앨범 정보와 트랙 목록이 포함되어 있습니다.

Python으로 배우는 API 입문

복잡한 데이터 구조: JSON

  • JSON
    • JavaScript Object Notation
    • 광범위하게 지원됨
    • 사람과 기계 모두 사용 가능
  • Content-type, mime-type 또는 media-type
  • 기타 형식
    • XML
    • CSV
    • YAML

앨범 API 응답

HTTP 200 OK 상태의 앨범 API 응답. 헤더에 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 입문

연습해 봅시다!

Python으로 배우는 API 입문

Preparing Video For Download...