본문 바로가기

Python

Python 과 API

API 란?

API라는 것은 무었일까?

 

우리가 어떠한 회사가 운영하고 있는 프로그램의 기능을 직접적으로 인간이 아닌 기계를 이용해서 만들고 싶을때 사용하는 것이라고 이해하면 된다.

이 때문에 API는 자동화를 하고싶을때 불안정한 web scraper을 이용하고싶지 않다면 필수적인 요소이다.

그러면 API에 대해서 자세히 살펴보자.

 

API란 다음과 같이 작동한다.

 

1. Client가 Server에게 request를 보내고

2. Server이 Client에게 responce를 보낸다. 

 

이렇게 말하면 간단하지만 자신의 코드에 넣어보려고 시도한 사람들은 어떻게 하는지 아이디어가 하나도 없을 것이다.

 

이해를 쉽게 돕기 위해서 오늘은 음악에 관한 api인  https://www.last.fm/api를 이용해볼 것 이다. 

 

Requests

 

Python에서 Server로 Request를 보내기 위해서는 Request 모듈을 사용할 것이다.

 

import requests

(Api를 부르고 받는데는 requests 하나만 있으면 된다. Json이나 다른 모듈들은 전혀 필요없다.)

 

 

Server에서 Request로 받는것은 보통 2가지가 있다. 하나는 header이고, 나머지 하나는 params 이다. 

 

그러면 Hello - Adele의 엘범 아트를 불러보자. 

이를 부르기 위해서는 track.getinfo라는 모듈을 사용할 것이다.

 

이 모듈을 사용하기 위한 Params는 다음과 같이 사이트에 나와있다.

 

 

mbid (Optional) : The musicbrainz id for the track
track (Required (unless mbid)] : The track name
artist (Required (unless mbid)] : The artist name
username (Optional) : The username for the context of the request. If supplied, the user's playcount for this track and whether they have loved the track is included in the response.
autocorrect[0|1] (Optional) : Transform misspelled artist and track names into correct artist and track names, returning the correct version instead. The corrected artist and track name will be returned in the response.
api_key (Required) : A Last.fm API key.

 

그러면 먼저 headers를 패키징해보자. 이 사이트에서는 헤더가 필요 없다 했음으로

headers = {
'user-agent': 'Mozilla/5.0'
}

user-agent 정도만 적어주면 된다. 

 

그러면 이번에는 params를 패키징해보자.

payload = {
'api_key': b73672ba11b09300fdf7bcd2a2db1863,
'method': 'track.getinfo',
'autocorrect':'1',
'track' : 'hello',
'artist': 'adele',
'format': 'json'
}

 요구조건을 따라 만들면 다음과 같이 간단하게 만들 수 있다. 그럼 이제 우리가 해야되는 것은 서버로 보내는 것이다.

 

r = requests.get('http://ws.audioscrobbler.com/2.0/', headers=headers, params=payload)

 

Response

 

그러면 서버는 Json 형식으로 우리에게 곡에 관한 정보를 돌려줄 것이다.

서버가 보내준 정보를 보자.

print(r.json())

>>> {'track': {'name': 'Hello', 'url': 'https://www.last.fm/music/Adele/_/Hello', 'duration': '295000',
'streamable': {'#text': '0', 'fulltrack': '0'}, 'listeners': '452639', 'playcount': '4593547', 'artist': {'name': 'Adele', 'mbid': 'cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493', 'url': 'https://www.last.fm/music/Adele'}, 'album': {'artist': 'Adele', 'title': '25', 'url': 'https://www.last.fm/music/Adele/25', 'image': [{'#text': 'https://lastfm.freetls.fastly.net/i/u/34s/d7122689fe7250d072f7b10d824f6ca9.png', 'size': 'small'}, {'#text': 'https://lastfm.freetls.fastly.net/i/u/64s/d7122689fe7250d072f7b10d824f6ca9.png', 'size': 'medium'}, {'#text': 'https://lastfm.freetls.fastly.net/i/u/174s/d7122689fe7250d072f7b10d824f6ca9.png', 'size': 'large'}, {'#text': 'https://lastfm.freetls.fastly.net/i/u/300x300/d7122689fe7250d072f7b10d824f6ca9.png', 'size': 'extralarge'}]}, 'toptags': {'tag': [{'name': 'soul', 'url': 'https://www.last.fm/tag/soul'}, {'name': 'pop', 'url': 'https://www.last.fm/tag/pop'}, {'name': '2015', 'url': 'https://www.last.fm/tag/2015'}, {'name': 'british', 'url': 'https://www.last.fm/tag/british'}, {'name': 'female vocalists', 'url': 'https://www.last.fm/tag/female+vocalists'}]}, 'wiki': {'published': '26 Oct 2015, 10:56', 'summary': '"Hello" was the first single released from
Adele\'s long awaited third studio album "25". The track was released on Friday, October 23, 2015 and soon went on to break a number of records. It went straight to No. 1 in Billboard\'s Hot 100 (November 14, 2015) -  which combines digital sales, radio airplay and streaming data - and became the first song to sell over 1 million downloads in 1 week. The video broke VEVO\'s "most viewed video in 24 hours", getting over 27. <a href="http://www.last.fm/music/Adele/_/Hello">Read more on Last.fm</a>.', 'content': '"Hello" was the first single released from Adele\'s long awaited third studio album
"25". The track was released on Friday, October 23, 2015 and soon went on to break a number of records. It went straight to No. 1 in Billboard\'s Hot 100 (November 14, 2015) -  which combines digital
sales, radio airplay and streaming data - and became the first song to sell over 1 million downloads in 1 week. The video broke VEVO\'s "most viewed video in 24 hours", getting over 27.7 million views: the record was previously held by Taylor Swift with "Bad Blood" (20.1 million video views). "Hello" is Adele’s fourth No. 1 song, following “Rolling In the Deep,” “Someone Like You” and “Set F
ire to the Rain.”\n\nGrammy Awards (2017) - At the 59th Grammy Awards on Sun, February 12, 2017, "H
ello" won a Grammy for "Song Of The Year" and "Best Pop Solo Performance". <a href="http://www.last.fm/music/Adele/_/Hello">Read more on Last.fm</a>. User-contributed text is available under the Creative Commons By-SA License; additional terms may apply.'}}}

다음과 같이 엄청 긴 딕셔너리를 돌려줄것이다. 

 

우리는 여기에서 우리가 원하는 정보를 찾아야 한다.

하지만 이렇게 나열된 정보는 보기가 불편하다. 따라서 https://jsoneditoronline.org/# 에서 json에디터를 이용해보자.

다음과 같이 깔끔하게 나열된 것을 볼 수 있다.

우리가 원하는 앨범 아트의 링크는 track/album/image/3/#text 에 저장되있음을 알 수 있다.

그러면 위 r.json()에서 링크를 찾아보자.

album_art = r.json()['track']['album']['image'][3]['#text']
print(album_art)

>>> https://lastfm.freetls.fastly.net/i/u/300x300/d7122689fe7250d072f7b10d824f6ca9.png

다음과 같이 링크를 돌려주는것을 관찰할 수 있다.