接入教程
访问 https://kinduff.github.io/dog-api/ 查看文档,使用GET请求访问端点获取随机狗事实
使用requests库获取狗事实
python
import requests
url = 'https://dog-api.kinduff.com/api/facts'
params = {'number': 3}
response = requests.get(url, params=params)
if response.status_code == &200:
data = response.json()
facts = data.get('facts', [])
for fact in facts:
print(fact)
else:
print(f'Error: {response.status_code}')
使用cURL调用狗事实API
php
<?php
$url = 'https://dog-api.kinduff.com/api/facts?number=2';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$data = json_decode($response, true);
$facts = $data['facts'] ?? [];
foreach ($facts as $fact) {
echo $fact . "\n";
}
} else {
echo "Error: " . $httpCode;
}
?>
使用fetch API获取随机狗事实
javascript
const url = 'https://dog-api.kinduff.com/api/facts';
const params = new URLSearchParams({ number: 1 });
fetch(`${url}?${params}`)
.then(response => {
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
return response.json();
})
.then(data => {
const facts = data.facts || [];
facts.forEach(fact => console.log(fact));
})
.catch(error => console.error('Error:', error));
常见问题
这个API需要认证或API密钥吗?
不需要,Dog Facts API是完全免费的开放API,无需认证或API密钥即可使用。
API请求频率有限制吗?
该API对合理使用没有严格的速率限制,但建议避免过度频繁的请求以保持服务稳定。
可以一次获取多个狗事实吗?
可以,通过'number'查询参数可以指定获取的事实数量,例如?number=5将返回5个随机狗事实。
Aitishiku.com