เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Basic Authentication ด้วย requests

Basic Authentication คือวิธีการยืนยันตัวตนที่ง่ายที่สุดสำหรับ web API โดยทำงานคล้ายกับการเข้าสู่ระบบเว็บไซต์ทั่วไป คือต้องส่ง username และ password พร้อมกับทุก request เพื่อให้ API ระบุตัวตนและอนุญาตให้เข้าถึงข้อมูลที่ร้องขอได้

มาเรียนรู้กันก่อนว่า server ตอบสนองอย่างไรเมื่อการยืนยันตัวตนล้มเหลว แล้วจึงแก้ไขโดยใช้ Basic Authentication

ข้อมูลที่ควรทราบ:

  1. ได้ import แพ็กเกจ requests ไว้แล้ว
  2. ใช้ username [email protected] และ password Warp_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')
แก้ไขและรันโค้ด