Basic Authentication ด้วย requests
Basic Authentication คือวิธีการยืนยันตัวตนที่ง่ายที่สุดสำหรับ web API โดยทำงานคล้ายกับการเข้าสู่ระบบเว็บไซต์ทั่วไป คือต้องส่ง username และ password พร้อมกับทุก request เพื่อให้ API ระบุตัวตนและอนุญาตให้เข้าถึงข้อมูลที่ร้องขอได้
มาเรียนรู้กันก่อนว่า server ตอบสนองอย่างไรเมื่อการยืนยันตัวตนล้มเหลว แล้วจึงแก้ไขโดยใช้ Basic Authentication
ข้อมูลที่ควรทราบ:
- ได้ import แพ็กเกจ
requestsไว้แล้ว - ใช้ username
[email protected]และ passwordWarp_ExtrapolationsForfeited2ในการยืนยันตัวตน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับ API
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
response = requests.get('http://localhost:3000/albums')
# Check if the status code on the response object matches a successful response
if(response.____ == ____):
print("Success!")
# Check if the status code indicates a failed authentication attempt
elif(response.____ == ____):
print('Authentication failed')
else:
print('Another error occurred')