urllib で API リクエスト
このコースでは、Music Catalog アプリケーションの API を使います。この API には複数の機能があります。まずは Lyrics API から始めましょう。これは Lyric of the day(本日の歌詞)から引用を取得できます。
最初の API リクエストを送る前に、その API にどこからアクセスできるかを知っておく必要があります。この場所は URL(Uniform Resource Locator)とも呼ばれます。URL は、API リクエストをPythonが「どこに」送ればよいかを示します。Lyrics API の URL は次のとおりです: http://localhost:3000/lyrics/。
まずは組み込みの urllib モジュールを使って、Lyrics API に最初のリクエストを送ってみましょう。
この演習はコースの一部です
Python で学ぶ API 入門
演習の手順
- レスポンスオブジェクトに対して
read関数を使い、レスポンスデータを読み込みます。 decode関数を使い、取得したレスポンスデータを適切なエンコーディングで文字列にデコードします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
from urllib.request import urlopen
with urlopen('http://localhost:3000/lyrics/') as response:
# Use the correct function to read the response data from the response object
data = response.____()
encoding = response.headers.get_content_charset()
# Decode the response data so you can print it as a string later
string = data.____(encoding)
print(string)