โครงสร้างพื้นฐานของ API request

Python เบื้องต้นสำหรับ API

Chris Ramakers

Engineering Manager

URL คืออะไร?

  • URL = Uniform Resource Locator
  • ที่อยู่แบบมีโครงสร้างสำหรับเข้าถึง API Resource
  • ปรับแต่ง URL เพื่อโต้ตอบกับ API Resource ที่ต้องการ
http://350.5th-ave.com/unit/243
Python เบื้องต้นสำหรับ API

วิเคราะห์โครงสร้าง URL

ไดอะแกรมแสดงส่วนประกอบต่าง ๆ ของ URL ได้แก่ Protocol (http://), Domain (350.5th-ave.com), Port (:80), Path (/unit/243) และ Query (?floor=77)

  • Protocol = วิธีการขนส่ง
  • Domain = ที่อยู่ของอาคารสำนักงาน
  • Port = ประตูหรือทางเข้าอาคาร
  • Path = ยูนิตสำนักงานที่ต้องการภายในอาคาร
  • Query = คำสั่งเพิ่มเติม
Python เบื้องต้นสำหรับ API

การเพิ่ม query parameter ด้วย requests

# Append the query parameter to the URL string
response = requests.get('http://350.5th-ave.com/unit/243?floor=77&elevator=True')
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
  • ใช้อาร์กิวเมนต์ params เพื่อเพิ่ม query parameter
# Create dictionary
query_params = {'floor': 77, 'elevator': True}
# Pass the dictionary using the `params` argument
response = requests.get('http://350.5th-ave.com/unit/243', params=query_params)
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
Python เบื้องต้นสำหรับ API

HTTP Verbs

  • ปลายทาง: ยูนิต 243 ของอาคารสำนักงาน 350 5th Ave
  • URL: http://350.5th-ave.com/unit/243

Actions

Verb Action คำอธิบาย
GET Read ตรวจสอบเนื้อหาในกล่องจดหมาย
POST Create ใส่พัสดุใหม่เข้าไปในกล่องจดหมาย
PUT Update แทนที่พัสดุทั้งหมดด้วยชิ้นใหม่
DELETE Delete นำพัสดุทั้งหมดออกจากกล่องจดหมาย
1 HTTP verb มีทั้งหมด 9 ประเภท แต่สำหรับ REST API แบบพื้นฐาน ใช้เพียง 4 ประเภทนี้
Python เบื้องต้นสำหรับ API

การส่งข้อมูลด้วย POST และ PUT

# GET = Retrieve a resource
response = requests.get('http://350.5th-ave.com/unit/243')

# POST = Create a resource response = requests.post('http://350.5th-ave.com/unit/243', data={"key": "value"}) # PUT = Update an existing resource response = requests.put('http://350.5th-ave.com/unit/243', data={"key": "value"})
# DELETE = Remove a resource response = requests.delete('http://350.5th-ave.com/unit/243')
  • แต่ละ verb มีเมธอดของตัวเองในแพ็กเกจ requests
  • ใช้อาร์กิวเมนต์ data เพื่อส่งข้อมูลใน POST หรือ PUT request
Python เบื้องต้นสำหรับ API

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับ API

Preparing Video For Download...