代码示例
丰富的示例代码,覆盖主流语言与场景
cURL 请求示例
GET 请求
curl -X GET "https://api.apibyte.cn/v2/weather?city=深圳" \
-H "Authorization: Bearer sk-your-key"
POST 请求
curl -X POST "https://api.apibyte.cn/v2/sms/send" \
-H "Authorization: Bearer sk-your-key" \
-H "Content-Type: application/json" \
-d '{"phone":"13800138000","template":"verify"}'前端调用示例
Fetch API
async function getWeather(city) {
const res = await fetch(`https://api.apibyte.cn/v2/weather?city=${city}`, {
headers: { 'Authorization': 'Bearer sk-your-key' }
});
return await res.json();
}
Axios
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.apibyte.cn/v2',
headers: { 'Authorization': 'Bearer sk-your-key' }
});
const { data } = await api.get('/weather', { params: { city: '深圳' } });
注意:前端直接调用会暴露 API Key,生产环境建议通过后端代理转发。
后端调用示例
Node.js
const axios = require('axios');
const res = await axios.get('https://api.apibyte.cn/v2/ip', {
params: { ip: '8.8.8.8' },
headers: { Authorization: 'Bearer ' + process.env.API_KEY }
});
Python
import requests
res = requests.get('https://api.apibyte.cn/v2/ip',
params={'ip': '8.8.8.8'},
headers={'Authorization': f'Bearer {API_KEY}'}
)
print(res.json())
PHP
$ch = curl_init('https://api.apibyte.cn/v2/ip?ip=8.8.8.8');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . env('API_KEY')
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch), true);批量请求示例
并发控制
当需要批量调用时,建议控制并发数以避免触发频率限制:
async function batchRequest(items, concurrency = 3) {
const results = [];
for (let i = 0; i < items.length; i += concurrency) {
const batch = items.slice(i, i + concurrency);
const batchResults = await Promise.all(
batch.map(item => fetchApi(item))
);
results.push(...batchResults);
// 间隔 200ms 避免触发 QPS 限制
if (i + concurrency < items.length) {
await new Promise(r => setTimeout(r, 200));
}
}
return results;
}