API 接入文档
完整的 API 接口使用说明,帮助开发者快速集成和调用
简介
欢迎使用 有熇个人博客 API 平台。我们提供丰富的 API 接口服务,涵盖数据查询、媒体处理、开发辅助、AI 接口等多种能力,帮助开发者快速集成到自己的应用中。
快速开始
只需 4 步即可开始调用 API 接口:
- 注册账号:访问 注册页面 创建账号
- 登录系统:使用账号密码登录系统
- 生成 API Key:进入用户中心 → API 密钥 → 生成新密钥
- 调用接口:使用生成的 Key 按照本文档调用对应 API
认证方式
所有 API 请求必须提供认证信息。支持两种方式:
方式一:URL 查询参数(推荐测试时使用)
GET https://blog.huangyouhe.cn/api/execute.php?api=接口slug&key=YOUR_API_KEY HTTP/1.1 Host: blog.huangyouhe.cn
方式二:HTTP 请求头(推荐生产环境使用)
GET https://blog.huangyouhe.cn/api/execute.php?api=接口slug HTTP/1.1 Host: blog.huangyouhe.cnX-API-Key: YOUR_API_KEY Content-Type: application/json
响应格式
所有 API 响应均为标准 JSON 格式,包含三个基本字段:
| 字段 | 类型 | 说明 |
|---|---|---|
| code | int | 状态码,200 表示成功,4xx/5xx 表示错误 |
| msg | string | 状态描述信息 |
| data | object/array | 具体的响应数据,结构因接口而异 |
{
"code": 200,
"msg": "success",
"data": {
// 具体接口返回的数据
}
}
计费说明
平台支持多种访问模式,满足不同用户需求:
| 类型 | 说明 | 适用用户 |
|---|---|---|
| 免费 | 所有用户均可免费调用,不消耗次数和余额 | 所有注册用户 |
| VIP 专属 | 仅 VIP/SVIP 会员可调用 | VIP 或 SVIP 会员 |
| SVIP 专属 | 仅 SVIP 会员可调用 | SVIP 会员 |
| 按次计费 | 每次调用从账户余额扣除费用 | 所有注册用户(余额充足) |
频率限制
为保障系统稳定和公平使用,平台对 API 调用做以下限制:
- 默认频率限制:每个密钥每分钟最多 60 次
- 自定义限制:用户可在密钥设置中为每个密钥单独配置频率限制
- 最小间隔:部分接口可设置最小调用间隔(秒)
- 最大调用量:可在密钥中设置最大调用次数,用完后自动停用
- 超限响应:超过限制将返回 HTTP 429 状态码
错误码说明
| HTTP 状态码 | 说明 | 建议操作 |
|---|---|---|
| 200 | 请求成功 | 正常处理返回数据 |
| 400 | 请求参数错误 | 检查必填参数是否完整、格式是否正确 |
| 401 | API 密钥无效或未提供 | 检查密钥是否正确、是否已过期 |
| 402 | 余额不足 | 充值或更换免费接口 |
| 403 | 权限不足 | 升级到相应会员等级 |
| 404 | 接口不存在 | 检查接口 slug 是否正确 |
| 429 | 请求过于频繁 | 降低调用频率或升级频率限制 |
| 500 | 服务器内部错误 | 联系管理员或稍后重试 |
| 503 | 接口暂不可用(维护中) | 等待接口恢复 |
PHP 接入示例
<?php
// 引入文件
$apiKey = "YOUR_API_KEY";
$url = "https://blog.huangyouhe.cn/api/execute.php";
// 方式一:GET 请求
$ch = curl_init($url . "?api=接口slug&key=" . urlencode($apiKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if ($result["code"] == 200) {
echo "调用成功: " . json_encode($result["data"]);
} else {
echo "错误: " . $result["msg"];
}
// 方式二:带业务参数的 GET 请求
$params = [
"api" => "接口slug",
"key" => $apiKey,
"param1" => "value1",
];
$ch = curl_init($url . "?" . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: " . $apiKey]);
$response = curl_exec($ch);
curl_close($ch);
// 方式三:POST 请求
$postData = [
"api" => "接口slug",
"param1" => "value1",
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: " . $apiKey]);
$response = curl_exec($ch);
curl_close($ch);
Python 接入示例
import requests
api_key = "YOUR_API_KEY"
url = "https://blog.huangyouhe.cn/api/execute.php"
# 方式一:GET 请求
params = {
"api": "接口slug",
"key": api_key,
"param1": "value1",
}
headers = {"X-API-Key": api_key}
response = requests.get(url, params=params, headers=headers, timeout=30)
data = response.json()
if data["code"] == 200:
print("成功:", data["data"])
else:
print("错误:", data["msg"])
# 方式二:POST 请求
data = {
"api": "接口slug",
"param1": "value1",
}
response = requests.post(url, json=data, headers=headers, timeout=30)
result = response.json()
JavaScript 接入示例
// 使用 fetch API
const apiKey = "YOUR_API_KEY";
const url = "https://blog.huangyouhe.cn/api/execute.php";
// 方式一:GET 请求
fetch(`${url}?api=接口slug&key=${apiKey}`, {
headers: { "X-API-Key": apiKey }
})
.then(res => res.json())
.then(data => {
if (data.code === 200) {
console.log("成功:", data.data);
} else {
console.log("错误:", data.msg);
}
})
.catch(err => console.error(err));
// 方式二:async/await
async function callApi(slug, params = {}) {
const query = new URLSearchParams({ api: slug, key: apiKey, ...params });
const res = await fetch(`${url}?${query}`, {
headers: { "X-API-Key": apiKey }
});
const data = await res.json();
if (data.code !== 200) throw new Error(data.msg);
return data.data;
}
// 使用
callApi("接口slug", { param1: "value1" })
.then(data => console.log(data))
.catch(err => console.error(err));
cURL 示例
# 使用 URL 参数
curl -X GET "https://blog.huangyouhe.cn/api/execute.php?api=接口slug&key=YOUR_API_KEY"
# 使用请求头(推荐)
curl -X GET "https://blog.huangyouhe.cn/api/execute.php?api=接口slug¶m1=value1" \
-H "X-API-Key: YOUR_API_KEY"
# POST 请求
curl -X POST "https://blog.huangyouhe.cn/api/execute.php" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "api=接口slug¶m1=value1"
# POST JSON 数据
curl -X POST "https://blog.huangyouhe.cn/api/execute.php" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"api": "接口slug", "param1": "value1"}'
Java 接入示例
JDK 11+ 内置 HttpClient:
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.StringJoiner;
public class ApiDemo {
private static final String API_KEY = "YOUR_API_KEY";
private static final String API_URL = "https://blog.huangyouhe.cn/api/execute.php";
public static void main(String[] args) throws Exception {
// GET 请求
StringJoiner sj = new StringJoiner("&");
sj.add(URLEncoder.encode("api", StandardCharsets.UTF_8) + "=" + URLEncoder.encode("接口slug", StandardCharsets.UTF_8));
sj.add(URLEncoder.encode("key", StandardCharsets.UTF_8) + "=" + URLEncoder.encode(API_KEY, StandardCharsets.UTF_8));
sj.add(URLEncoder.encode("param1", StandardCharsets.UTF_8) + "=" + URLEncoder.encode("value1", StandardCharsets.UTF_8));
String url = API_URL + "?" + sj.toString();
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", API_KEY)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("HTTP " + resp.statusCode());
System.out.println(resp.body());
// POST 请求
String postBody = "api=接口slug¶m1=value1";
HttpRequest postReq = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", API_KEY)
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(postBody))
.build();
HttpResponse<String> postResp = client.send(postReq, HttpResponse.BodyHandlers.ofString());
System.out.println("POST HTTP " + postResp.statusCode());
System.out.println(postResp.body());
}
}
Go 接入示例
标准库 net/http(Go 1.16+):
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
APIKey = "YOUR_API_KEY"
APIURL = "https://blog.huangyouhe.cn/api/execute.php"
)
type ApiResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func main() {
client := &http.Client{Timeout: 30 * time.Second}
// GET 请求
req, _ := http.NewRequest("GET", APIURL, nil)
q := req.URL.Query()
q.Set("api", "接口slug")
q.Set("key", APIKey)
q.Set("param1", "value1")
req.URL.RawQuery = q.Encode()
req.Header.Set("X-API-Key", APIKey)
req.Header.Set("Accept", "application/json")
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("HTTP", resp.Status)
var out ApiResp
if json.Unmarshal(body, &out) == nil && out.Code == 200 {
fmt.Printf("成功:%+v\n", out.Data)
} else {
fmt.Println("RAW:", string(body))
}
// POST 请求
postData := "api=接口slug¶m1=value1"
postReq, _ := http.NewRequest("POST", APIURL,
io.NopCloser(stringReader(postData)))
postReq.Header.Set("X-API-Key", APIKey)
postReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
postResp, _ := client.Do(postReq)
defer postResp.Body.Close()
postBody, _ := io.ReadAll(postResp.Body)
fmt.Println("POST HTTP", postResp.Status)
fmt.Println(string(postBody))
}
func stringReader(s string) *strings.Reader {
return strings.NewReader(s)
}
C# 接入示例
.NET 5+ / .NET Core:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
record ApiResp(int code, string msg, object data);
static class Program {
private const string ApiKey = "YOUR_API_KEY";
private const string ApiUrl = "https://blog.huangyouhe.cn/api/execute.php";
static async Task Main() {
using var http = new HttpClient();
http.Timeout = TimeSpan.FromSeconds(30);
http.DefaultRequestHeaders.Add("X-API-Key", ApiKey);
http.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// GET 请求
var query = new Dictionary<string, string> {
{ "api", "接口slug" },
{ "key", ApiKey },
{ "param1", "value1" }
};
using var content = new FormUrlEncodedContent(query);
var url = ApiUrl + "?" + await content.ReadAsStringAsync();
using var req = new HttpRequestMessage(HttpMethod.Get, url);
using var resp = await http.SendAsync(req);
var json = await resp.Content.ReadAsStringAsync();
Console.WriteLine("HTTP " + (int)resp.StatusCode);
var obj = JsonSerializer.Deserialize<ApiResp>(json);
Console.WriteLine(obj?.code == 200
? ("成功:" + obj.data)
: ("RAW: " + json));
// POST 请求
var postData = new Dictionary<string, string> {
{ "api", "接口slug" },
{ "param1", "value1" }
};
using var postContent = new FormUrlEncodedContent(postData);
using var postResp = await http.PostAsync(ApiUrl, postContent);
var postJson = await postResp.Content.ReadAsStringAsync();
Console.WriteLine("POST HTTP " + (int)postResp.StatusCode);
Console.WriteLine(postJson);
}
}
Ruby 接入示例
Ruby 2.5+ 标准库 Net::HTTP:
require "net/http"
require "uri"
require "json"
API_KEY = "YOUR_API_KEY".freeze
API_URL = "https://blog.huangyouhe.cn/api/execute.php".freeze
begin
# GET 请求
uri = URI.parse(API_URL)
uri.query = URI.encode_www_form(
api: "接口slug",
key: API_KEY,
param1: "value1"
)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")
http.open_timeout = 10
http.read_timeout = 30
req = Net::HTTP::Get.new(uri)
req["X-API-Key"] = API_KEY
req["Accept"] = "application/json"
resp = http.request(req)
puts "HTTP #{resp.code}"
data = JSON.parse(resp.body) rescue nil
if data && data["code"] == 200
puts "成功:#{data["data"].inspect}"
else
puts "RAW: #{resp.body}"
end
# POST 请求
post_req = Net::HTTP::Post.new(API_URL)
post_req["X-API-Key"] = API_KEY
post_req["Content-Type"] = "application/x-www-form-urlencoded"
post_req.body = URI.encode_www_form(api: "接口slug", param1: "value1")
post_resp = http.request(post_req)
puts "POST HTTP #{post_resp.code}"
puts post_resp.body
rescue => e
puts "异常:#{e.message}"
end
Swift 接入示例
iOS 13+ / macOS 10.15+ URLSession async/await:
import Foundation
let apiKey = "YOUR_API_KEY"
let apiURL = URL(string: "https://blog.huangyouhe.cn/api/execute.php")!
func callAPI() async {
// GET 请求
guard var comps = URLComponents(url: apiURL, resolvingAgainstBaseURL: false) else { return }
comps.queryItems = [
URLQueryItem(name: "api", value: "接口slug"),
URLQueryItem(name: "key", value: apiKey),
URLQueryItem(name: "param1", value: "value1")
]
var req = URLRequest(url: comps.url!)
req.httpMethod = "GET"
req.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
req.setValue("application/json", forHTTPHeaderField: "Accept")
req.timeoutInterval = 30
do {
let (data, resp) = try await URLSession.shared.data(for: req)
if let http = resp as? HTTPURLResponse { print("HTTP", http.statusCode) }
print(String(data: data, encoding: .utf8) ?? "")
} catch {
print("请求异常:", error)
}
// POST 请求
var postReq = URLRequest(url: apiURL)
postReq.httpMethod = "POST"
postReq.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
postReq.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
postReq.httpBody = "api=接口slug¶m1=value1".data(using: .utf8)
do {
let (postData, postResp) = try await URLSession.shared.data(for: postReq)
if let http = postResp as? HTTPURLResponse { print("POST HTTP", http.statusCode) }
print(String(data: postData, encoding: .utf8) ?? "")
} catch {
print("POST 异常:", error)
}
}
// 调用:Task { await callAPI() }
Kotlin 接入示例
Kotlin/JVM(JDK 11 HttpClient):
import java.net.URI
import java.net.URLEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.charset.StandardCharsets
import java.time.Duration
private const val API_KEY = "YOUR_API_KEY"
private const val API_URL = "https://blog.huangyouhe.cn/api/execute.php"
fun main() {
// GET 请求
val params = linkedMapOf(
"api" to "接口slug",
"key" to API_KEY,
"param1" to "value1"
)
val query = params.entries.joinToString("&") {
"${URLEncoder.encode(it.key, StandardCharsets.UTF_8)}=${URLEncoder.encode(it.value, StandardCharsets.UTF_8)}"
}
val url = "$API_URL?$query"
val client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build()
val request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", API_KEY)
.header("Accept", "application/json")
.GET()
.build()
val resp = client.send(request, HttpResponse.BodyHandlers.ofString())
println("HTTP ${resp.statusCode()}")
println(resp.body())
// POST 请求
val postBody = "api=接口slug¶m1=value1"
val postRequest = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", API_KEY)
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(postBody))
.build()
val postResp = client.send(postRequest, HttpResponse.BodyHandlers.ofString())
println("POST HTTP ${postResp.statusCode()}")
println(postResp.body())
}
PowerShell 接入示例
PowerShell 5.1 / PowerShell 7+(跨平台):
$ErrorActionPreference = "Stop"
$apiKey = "YOUR_API_KEY"
$apiURL = "https://blog.huangyouhe.cn/api/execute.php"
# GET 请求
$params = @{
"api" = "接口slug"
"key" = $apiKey
"param1" = "value1"
}
$headers = @{
"X-API-Key" = $apiKey
"Accept" = "application/json"
}
try {
$resp = Invoke-RestMethod -Uri $apiURL -Method GET `
-Headers $headers -Body $params -TimeoutSec 30
if ($resp.code -eq 200) {
Write-Host "成功:" $resp.data
} else {
Write-Host "失败:" $resp.msg
}
$resp | ConvertTo-Json -Depth 10 | Write-Host
} catch {
Write-Host "请求异常:" $_.Exception.Message
}
# POST 请求
$postBody = @{
"api" = "接口slug"
"param1" = "value1"
}
try {
$postResp = Invoke-RestMethod -Uri $apiURL -Method POST `
-Headers $headers -Body $postBody -ContentType "application/x-www-form-urlencoded" -TimeoutSec 30
$postResp | ConvertTo-Json -Depth 10 | Write-Host
} catch {
Write-Host "POST 异常:" $_.Exception.Message
}
Rust 接入示例
Rust 2021 Edition · reqwest + tokio:
use std::time::Duration;
use serde::Deserialize;
use reqwest::Client;
#[derive(Debug, Deserialize)]
struct ApiResp {
code: i32,
msg: String,
data: Option<serde_json::Value>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let client = Client::builder()
.timeout(Duration::from_secs(30))
.build()?;
// GET 请求
let resp = client
.get("https://blog.huangyouhe.cn/api/execute.php")
.query(&[
("api", "接口slug"),
("key", api_key),
("param1", "value1"),
])
.header("X-API-Key", api_key)
.header("Accept", "application/json")
.send()
.await?;
println!("HTTP {}", resp.status());
let out: ApiResp = resp.json().await?;
if out.code == 200 {
println!("成功:{:?}", out.data);
} else {
println!("失败 code={} msg={}", out.code, out.msg);
}
// POST 请求
let post_resp = client
.post("https://blog.huangyouhe.cn/api/execute.php")
.form(&[
("api", "接口slug"),
("param1", "value1"),
])
.header("X-API-Key", api_key)
.send()
.await?;
println!("POST HTTP {}", post_resp.status());
let post_out: ApiResp = post_resp.json().await?;
println!("{:?}", post_out);
Ok(())
}
/* Cargo.toml:
[dependencies]
reqwest = { version = "0.11", features = ["json", "query", "form"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
*/
C++ 接入示例
C++17 · libcurl + nlohmann/json(编译:g++ demo.cpp -o demo -lcurl):
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
using namespace std::string_literals;
using json = nlohmann::json;
static size_t write_cb(void* p, size_t s, size_t n, std::string* out) {
out->append(static_cast<char*>(p), s * n);
return s * n;
}
int main() {
const std::string api_key = "YOUR_API_KEY";
const std::string url = "https://blog.huangyouhe.cn/api/execute.php?key="s + api_key + "&api=接口slug¶m1=value1";
curl_global_init(CURL_GLOBAL_ALL);
CURL* h = curl_easy_init();
if (!h) return 1;
struct curl_slist* hs = nullptr;
hs = curl_slist_append(hs, ("X-API-Key: "s + api_key).c_str());
hs = curl_slist_append(hs, "Accept: application/json");
std::string body;
curl_easy_setopt(h, CURLOPT_URL, url.c_str());
curl_easy_setopt(h, CURLOPT_HTTPHEADER, hs);
curl_easy_setopt(h, CURLOPT_TIMEOUT, 30L);
curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(h, CURLOPT_WRITEDATA, &body);
CURLcode rc = curl_easy_perform(h);
long http = 0;
curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &http);
std::cout << "HTTP " << http << std::endl;
curl_slist_free_all(hs);
curl_easy_cleanup(h);
curl_global_cleanup();
if (rc != CURLE_OK) {
std::cerr << "curl err: " << curl_easy_strerror(rc);
return 2;
}
try {
auto j = json::parse(body);
if (j["code"].get<int>() == 200)
std::cout << "成功:" << j["data"].dump(2);
else
std::cout << "失败:" << j["msg"].get<std::string>();
} catch (...) {
std::cout << "RAW: " << body;
}
return 0;
}
C 语言接入示例
标准 C11 · libcurl(编译:gcc -O2 demo.c -o demo -lcurl):
/* C 语言调用示例 - libcurl */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
struct buf { char* data; size_t len; };
static size_t write_cb(void* p, size_t s, size_t n, struct buf* b) {
size_t add = s * n;
b->data = realloc(b->data, b->len + add + 1);
memcpy(b->data + b->len, p, add);
b->len += add;
b->data[b->len] = 0;
return add;
}
int main(void) {
const char api_key[] = "YOUR_API_KEY";
const char base[] = "https://blog.huangyouhe.cn/api/execute.php";
char url[4096];
snprintf(url, sizeof url, "%s?key=%s&api=接口slug¶m1=value1", base, api_key);
curl_global_init(CURL_GLOBAL_ALL);
CURL* h = curl_easy_init();
if (!h) return 1;
struct curl_slist* hs = NULL;
char xh[256];
snprintf(xh, sizeof xh, "X-API-Key: %s", api_key);
hs = curl_slist_append(hs, xh);
hs = curl_slist_append(hs, "Accept: application/json");
struct buf b = {0};
curl_easy_setopt(h, CURLOPT_URL, url);
curl_easy_setopt(h, CURLOPT_HTTPHEADER, hs);
curl_easy_setopt(h, CURLOPT_TIMEOUT, 30L);
curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(h, CURLOPT_WRITEDATA, &b);
CURLcode rc = curl_easy_perform(h);
long http_code = 0;
curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &http_code);
printf("HTTP %ld\n", http_code);
printf("%s\n", b.data ? b.data : "(空)");
free(b.data);
curl_slist_free_all(hs);
curl_easy_cleanup(h);
curl_global_cleanup();
return rc == CURLE_OK ? 0 : 2;
}
易语言接入示例
易语言 5.x / 火山中文编程(支持原生 HTTP 类 / 精易模块 / HP-Socket):
' =========================================
' API 通用调用示例(易语言 5.x)
' 支持:原生 HTTP 类 / 精易模块 / HP-Socket
' =========================================
.版本 2
.程序集 窗口程序集_启动窗口
.子程序 _按钮1_被单击, , , 【点击按钮调用接口】
.局部变量 API_KEY, 文本型
.局部变量 接口地址, 文本型
.局部变量 参数文本, 文本型
.局部变量 请求地址, 文本型
.局部变量 响应文本, 文本型
.局部变量 HTTP, HTTP类
API_KEY = "YOUR_API_KEY"
接口地址 = "https://blog.huangyouhe.cn/api/execute.php"
参数文本 = "key=" + API_KEY + "&api=接口slug¶m1=value1"
请求地址 = 接口地址 + "?" + 参数文本
HTTP.添加请求头 ("X-API-Key", API_KEY)
HTTP.添加请求头 ("Accept", "application/json")
' GET 请求:
响应文本 = HTTP.读文本 (请求地址, , , 30)
' 或 POST 请求:
' 响应文本 = HTTP.提交文本 (接口地址, "api=接口slug¶m1=value1", "application/x-www-form-urlencoded", , , 30)
调试输出 ("响应:", 响应文本)
编辑框_结果.内容 = 响应文本
' --- 使用【精易模块】写法 ---
' 编码_URLEncoder (参数文本)
' 网页_访问_对象 (请求地址, 0, 参数文本, , , "X-API-Key: " + API_KEY + #换行符 + "Accept: application/json" + #换行符)
Webhook 通知
当有重要 API 事件发生时(如调用失败、密钥用完等),系统可以向指定的 Webhook URL 发送 HTTP POST 请求。
请求格式
POST 到您配置的 webhook_url
Content-Type: application/json
X-Webhook-Source: API-System
{
"event": "api_call",
"endpoint": "接口名称",
"status": "success|failed",
"data": { /* 相关数据 */ },
"timestamp": "2026-08-01 12:00:00"
}
使用场景
- 监控 API 调用失败并及时告警
- 密钥调用量用完时通知用户
- 将 API 数据同步到其他系统
- 集成到 Slack、钉钉、飞书等 IM 工具
沙箱模式
管理员开启沙箱模式后,所有 API 将返回模拟数据而不会产生真实的扣费或副作用。适合开发和测试使用。
- 开启位置:后台 → API 管理 → API 设置
- 适用场景:开发调试、集成测试、演示 Demo
- 注意:沙箱模式下不会真实扣除余额和消耗调用次数
缓存机制
系统支持 API 响应缓存,相同的请求在缓存有效期内将直接返回缓存数据,显著提升响应速度。
- 缓存有效期:可在 API 设置中配置(默认 300 秒)
- 缓存键:基于 API Slug + 参数生成
- 缓存存储:服务器本地文件存储(storage/api_cache/)
- 注意:扣费类请求不参与缓存,确保计费准确
安全建议
密钥安全
- 不要将 API Key 提交到公开的代码仓库(GitHub 等)
- 建议在服务端环境变量中存储密钥,避免硬编码
- 生产环境使用独立的密钥,与开发环境分离
- 定期轮换密钥,设置合理的过期时间
访问控制
- 使用 IP 白名单限制密钥的使用 IP 范围
- 为不同应用创建独立的密钥,便于追踪和撤销
- 设置合理的最大调用次数和频率限制
错误处理
- 始终检查返回的
code字段判断调用是否成功 - 4xx 错误表示客户端问题(参数、权限等),5xx 错误表示服务端问题
- 实现指数退避的重试策略,避免频繁重试
- 记录失败日志便于排查问题
常见问题
Q: 为什么我的 API Key 调用返回 401 错误?
A: 可能原因:密钥不存在或已被禁用、密钥已过期、IP 不在白名单中。请登录用户中心检查密钥状态。
Q: 如何重置密钥的调用次数?
A: 登录用户中心 → API 密钥 → 找到对应密钥 → 点击"重置"按钮。
Q: 能否同时限制调用频率和调用总量?
A: 可以。在生成密钥时可分别设置"最大调用次数"和"频率限制(次/分钟)",两个限制同时生效。
Q: 按次计费接口如何扣费?
A: 调用时从账户余额扣除对应费用。VIP/SVIP 用户享受折扣。扣费失败会回滚请求,返回错误码。
Q: 支持哪些 HTTP 方法?
A: 支持 GET、POST、PUT、DELETE。具体每个接口支持的方法请查看对应接口文档。
Q: 能否批量调用 API?
A: 目前不支持批量调用,建议在服务端使用并发请求(如 curl_multi、asyncio.gather 等)自行实现。
Q: 数据格式支持什么?
A: GET 请求通过 URL 参数传递数据;POST 请求支持 application/x-www-form-urlencoded 和 application/json。