接入教程
1. 阅读授权指南以生成访问令牌
2. 获取API密钥并配置认证
3. 调用航班状态端点并传入航班号
4. 解析返回的JSON数据获取状态
5. 处理可能的错误响应
6. 在生产环境前先在测试环境验证
Python查询航班状态
import requests
# 配置API参数
base_url = 'https://api.example.com'
endpoint = '/v2/shopping/flight-offers'
api_key = 'YOUR_API_KEY'
# 设置请求头
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
# 构建查询参数
params = {
'originLocationCode': 'JFK',
'destinationLocationCode': 'LAX',
'departureDate': '2024-01-15',
'adults': 1
}
# 发送请求
try:
response = requests.get(f'{base_url}{endpoint}',
headers=headers,
params=params)
response.raise_for_status()
flight_data = response.json()
print('航班查询成功:', flight_data)
except requests.exceptions.RequestException as e:
print('请求失败:', str(e))
PHP获取航班信息
<?php
$baseUrl = 'https://api.example.com';
$endpoint = '/v2/shopping/flight-offers';
$apiKey = 'YOUR_API_KEY';
// 构建查询参数
$queryParams = [
'originLocationCode' => 'JFK',
'destinationLocationCode' => 'LAX',
'departureDate' => '2024-01-15',
'adults' => 1
];
// 初始化cURL
$ch = curl_init();
$url = $baseUrl . $endpoint . '?' . http_build_query($queryParams);
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
],
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo '请求错误: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode === 200) {
$flightData = json_decode($response, true);
echo '航班数据获取成功';
print_r($flightData);
} else {
echo 'HTTP错误代码: ' . $httpCode;
}
}
curl_close($ch);
?>
JavaScript航班状态查询
const fetch = require('node-fetch'); // Node.js环境
async function getFlightStatus() {
const baseUrl = 'https://api.example.com';
const endpoint = '/v2/shopping/flight-offers';
const apiKey = 'YOUR_API_KEY';
// 构建查询参数
const queryParams = new URLSearchParams({
originLocationCode: 'JFK',
destinationLocationCode: 'LAX',
departureDate: '2024-01-15',
adults: 1
});
const url = `${baseUrl}${endpoint}?${queryParams}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const flightData = await response.json();
console.log('航班查询成功:', flightData);
return flightData;
} catch (error) {
console.error('请求失败:', error.message);
throw error;
}
}
// 调用函数
getFlightStatus().catch(console.error);
常见问题
如何获取API访问令牌?
访问令牌需要通过OAuth 2.0认证流程获取。首先在开发者门户注册应用获取客户端ID和密钥,然后按照授权指南通过令牌端点交换访问令牌。测试环境令牌有效期较短,生产环境需根据套餐确定有效期。
测试环境和生产环境有什么区别?
测试环境使用生产数据的子集,返回的航班信息可能有限,且请求频率限制较低。生产环境提供完整实时数据,但需要商业订阅和更高的认证要求。建议先在测试环境完成集成测试。
API支持哪些查询参数?
基础查询参数包括出发地机场代码、目的地机场代码、出发日期和乘客数量。高级参数可包含航空公司代码、航班号、舱位等级等。具体参数请参考官方API文档,不同套餐支持的参数可能不同。
Aitishiku.com