接入教程
1.访问官网查看文档
2.选择目标国家代码
3.调用节假日查询接口
4.处理返回的JSON数据
5.集成到您的应用程序中
使用Python查询指定年份的节假日
python
import requests
base_url = 'https://date.nager.at/api/v3'
country_code = 'CN' # 示例国家代码:中国
year = 2024
url = f'{base_url}/PublicHolidays/{year}/{country_code}'
response = requests.get(url)
if response.status_code == 200:
holidays = response.json()
for holiday in holidays:
print(f"{holiday['date']}: {holiday['name']}")
else:
print(f"请求失败,状态码: {response.status_code}")
使用PHP获取指定国家的节假日列表
php
<?php
$base_url = 'https://date.nager.at/api/v3';
$country_code = 'US';
$year = 2024;
$url = $base_url . '/PublicHolidays/' . $year . '/' . $country_code;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code == 200) {
$holidays = json_decode($response, true);
foreach ($holidays as $holiday) {
echo $holiday['date'] . ': ' . $holiday['name'] . "\n";
}
} else {
echo '请求失败,状态码: ' . $http_code . "\n";
}
?>
使用JavaScript获取当前年份的节假日
javascript
const baseUrl = 'https://date.nager.at/api/v3';
const countryCode = 'GB';
const currentYear = new Date().getFullYear();
const url = `${baseUrl}/PublicHolidays/${currentYear}/${countryCode}`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(holidays => {
holidays.forEach(holiday => {
console.log(`${holiday.date}: ${holiday.name}`);
});
})
.catch(error => {
console.error('请求失败:', error);
});
常见问题
这个API需要API密钥吗?
Nager.Date API目前完全免费且无需任何API密钥或身份验证即可使用。您可以直接调用其公开端点获取数据。
如何查询特定国家的节假日?
您需要知道该国家的两位字母ISO 3166-1 alpha-2代码(例如CN代表中国,US代表美国),并将其作为路径参数与年份一起传入相应的API端点。
API返回的数据格式是什么?
API默认返回JSON格式的数据。每个节假日对象通常包含日期、名称、是否为全球性假日等字段。您可以通过请求头指定接受`application/json`。
Aitishiku.com