การส่ง API request ด้วย urllib
ในคอร์สนี้ เราจะใช้ API ของแอปพลิเคชัน Music Catalog ซึ่งมีฟีเจอร์หลายอย่าง เริ่มต้นด้วย Lyrics API ที่ช่วยให้ดึงข้อความจาก Lyric of the day ได้
ก่อนจะส่ง API request ครั้งแรก ต้องรู้ก่อนว่า API อยู่ที่ไหน ตำแหน่งนี้เรียกว่า URL ย่อมาจาก Uniform Resource Locator ซึ่งบอก Python ว่าจะส่ง API request ไปที่ใด URL ของ Lyrics API คือ: http://localhost:3000/lyrics/
มาส่ง request แรกไปยัง Lyrics API โดยใช้โมดูล urllib ที่มีมาให้พร้อมใน Python กัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับ API
คำแนะนำการฝึกหัด
- เรียกใช้ฟังก์ชัน
readบนออบเจกต์ response เพื่ออ่านข้อมูลที่ได้รับ - เรียกใช้ฟังก์ชัน
decodeเพื่อแปลงข้อมูล response ให้เป็น string ด้วย encoding ที่ถูกต้อง
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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)