การยืนยันตัวตน
การเรียกใช้งาน API ทั้งหมดของ GenderAPI ต้องมีการยืนยันตัวตน คุณสามารถยืนยันตัวตนได้ 2 วิธี:
- ใส่ API Key ลงใน POST body เป็นพารามิเตอร์
key
- ใส่ API Key ใน Authorization header โดยใช้ Bearer token
1. ใส่ API Key ใน POST Body
วิธีที่ง่ายที่สุดคือการใส่ API key ของคุณลงในฟิลด์ key
ภายใน JSON body ของคำขอ POST
ตัวอย่างการตรวจสอบเพศจากชื่อ "Alice":
ตัวอย่าง cURL
curl -X POST "https://api.genderapi.io/api" \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "key": "YOUR_API_KEY"}'
ตัวอย่าง JavaScript fetch
fetch("https://api.genderapi.io/api", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Alice",
key: "YOUR_API_KEY"
})
})
.then(response => response.json())
.then(data => console.log(data));
ตัวอย่าง Python requests
import requests
url = "https://api.genderapi.io/api"
payload = {
"name": "Alice",
"key": "YOUR_API_KEY"
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
2. ใส่ API Key ใน Authorization Header (Bearer Token)
เพื่อความปลอดภัยที่มากขึ้น คุณสามารถใส่ API key ลงใน Authorization header โดยใช้ Bearer scheme วิธีนี้ ไม่ต้อง ใส่ API key ลงใน JSON body
ให้ใส่เฉพาะพารามิเตอร์ที่ต้องการ (เช่น name
) ลงใน POST body เท่านั้น
ตัวอย่างการตรวจสอบเพศจากชื่อ "Alice":
ตัวอย่าง cURL
curl -X POST "https://api.genderapi.io/api" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"name": "Alice"}'
ตัวอย่าง JavaScript fetch
fetch("https://api.genderapi.io/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
},
body: JSON.stringify({
name: "Alice"
})
})
.then(response => response.json())
.then(data => console.log(data));
ตัวอย่าง Python requests
import requests
url = "https://api.genderapi.io/api"
payload = {
"name": "Alice"
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
เลือกใช้วิธีใด?
ทั้งสองวิธีสามารถใช้ได้กับทุก API endpoint อย่างไรก็ตาม การใช้ Authorization header จะปลอดภัยกว่าเพราะหลีกเลี่ยงการใส่ API key ลงใน body ของคำขอ
ไม่ว่าจะใช้วิธีใด อย่าลืมตั้งค่า header Content-Type
เป็น
application/json
เสมอเมื่อทำ POST request