身份验证 (Authentication)
所有向 GenderAPI 发起的 API 请求都需要身份验证。你可以通过两种方式进行身份验证:
- 在 POST 请求体中以
key
参数的形式传入 API Key - 在 Authorization 请求头中传入 API Key,使用 Bearer token
1. 在 POST 请求体中传入 API Key
最简单的身份验证方式是将你的 API Key 作为名为 key
的字段,放在 POST 请求的 JSON 请求体中。
例如,要判断名字 “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. 在 Authorization 请求头中传入 API Key (Bearer Token)
为了更高的安全性和更简洁的请求,你可以在 Authorization 请求头中,使用 Bearer 模式发送你的 API Key。 在这种方法中,不需要在 JSON 请求体中包含 API Key。
取而代之的是,只有你的输入参数(例如 name
)会放在 POST 请求体中。
例如,要判断名字 “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 请求头更加安全, 因为这样可以避免在请求体里暴露你的 API Key,从而防止不小心被记录到日志中。
不管你选择哪种方式,在发送 POST 请求时,都应当始终将 Content-Type
请求头设置为
application/json
。