파이썬은 신이다
import requests, json
from pprint import pprint
winner_url = f"https://jsonmock.hackerrank.com/api/football_competitions?name={competition}&year={year}"
#response = requests.get(winner_url).json()
winner_team = requests.get(winner_url).json()['data'][0]['winner']
#pprint(response)
match_url = f"https://jsonmock.hackerrank.com/api/football_matches?competition={competition}&year={year}"
total_pages = int(requests.get(match_url).json()['total_pages'])
f"https://url?param={param_val}" : 손쉽게 url에 파라미터 넣자request.get(url) : response code 반환request.get(url).json : 역직렬화해야 데이터가 제대로 출력됨winner_team = requests.get(winner_url).json()['data'][0]['winner'] : 반환값은 딕셔너리 혹은 리스트 형태이므로, 복잡하게 변수에 할당해가며 탐색하지 말고 바로 인덱싱paramDict = {
"a" : "aa",
"b" : 123
}
response = requests.get(url, params=paramDict)
data = {
"a" : "aa",
"b" : 123
}
response = requests.post(url, data=data)
headers = {'User-Agent': 'MyUserAgent/1.0'}
response = requests.get(url, headers=headers)
대게 requests.get(url).json() 선에서 해결되기는 하지만, 조바심에 정리해 본다
>>> import json
>>> d = {"name":"홍길동", "birth":"0525", "age": 30}
>>> json_data = json.dumps(d)
>>> json_data
'{"name": "\\ud64d\\uae38\\ub3d9", "birth": "0525", "age": 30}'
>>> json.loads(json_data)
{'name': '홍길동', 'birth': '0525', 'age': 30}
적극 활용하자
winner_url = f"https://jsonmock.hackerrank.com/api/football_competitions?name={competition}&year={year}"
response = requests.get(winner_url).json()
pprint(response)

알고리즘 문제와 달리 비즈니스 요구사항에 맞게 HTTP 요청을 다루고 API 데이터를 가공하는 것에 핵심이 있는 것으로 보인다. 따라서 문제에 해답과 함정이 있다면, 설명에 있다. 다음을 주의해서 보자