urllib के साथ API requests
इस कोर्स के लिए, आप एक Music Catalog एप्लिकेशन की API का उपयोग करेंगे. इस API में कई फीचर्स हैं. आप Lyrics API से शुरू करेंगे, जो आपको Lyric of the day से एक quote प्राप्त करने देता है.
पहली API request करने से पहले, आपको जानना होगा कि API कहाँ उपलब्ध है. इस लोकेशन को URL (Uniform Resource Locator) भी कहा जाता है. URL Python को यह बताता है कि API request कहाँ भेजनी है. Lyrics API का URL है: http://localhost:3000/lyrics/.
आइए, बिल्ट-इन Python मॉड्यूल urllib का उपयोग करके Lyrics API को पहली request भेजते हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में APIs परिचय
अभ्यास निर्देश
- response ऑब्जेक्ट पर
readफंक्शन का उपयोग करके response डेटा पढ़ें. - सही encoding के साथ response डेटा को string में बदलने के लिए
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)