Headers และ status codes

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

Chris Ramakers

Engineering Manager

โครงสร้างของข้อความ request และ response

ตัวอย่างข้อความ request และ response พร้อม headers และ response body แบบ JSON

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

Start-line

ตัวอย่างสามส่วนหลักของข้อความ request หรือ response โดยไฮไลต์ส่วน start line

  • เซิร์ฟเวอร์จะ ส่ง status code ที่เป็นตัวเลขในข้อความ response เสมอ
Python เบื้องต้นสำหรับ API

Status codes

หมวดหมู่ของ status code

  • 1XX: Informational responses
  • 2XX: Successful responses
  • 3XX: Redirection messages
  • 4XX: Client error responses
  • 5XX: Server error responses

Status codes ที่ใช้บ่อย

  • 200: OK
  • 404: Not Found
  • 500: Internal Server Error
1 ดู status code ทั้งหมดได้ที่หน้า MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Python เบื้องต้นสำหรับ API

Headers

ตัวอย่างสามส่วนหลักของข้อความ request หรือ response โดยไฮไลต์ส่วน headers

key1: Value 1
key2: Value 2
Python เบื้องต้นสำหรับ API

ตัวอย่าง: Content negotiation ด้วย headers

ตัวอย่างสามส่วนหลักของข้อความ request หรือ response โดยไฮไลต์ส่วน headers

  • ฝั่ง client เพิ่ม header accept: application/json ใน request
  • เซิร์ฟเวอร์ตอบกลับพร้อม header content-type: application/json
Python เบื้องต้นสำหรับ API

การใช้ headers กับ requests

# Adding headers to a request
response = requests.get(
  'https://api.datacamp.com', 
  headers={'accept':'application/json'}
)
# Reading response headers
response.headers['content-type']
'application/json'
response.headers.get('content-type')
'application/json'
Python เบื้องต้นสำหรับ API

การใช้ status codes กับ requests

# Accessing the status code
response = requests.get('https://api.datacamp.com/users/12')

response.status_code == 200
True
# Looking up status codes using requests.codes
response = requests.get('https://api.datacamp.com/this/is/the/wrong/path')

response.status_code == requests.codes.not_found
True
Python เบื้องต้นสำหรับ API

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

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

Preparing Video For Download...