API 文档
CarefreeCMS 提供了完整的 RESTful API,方便与其他系统集成或进行二次开发。
API 概述
基础信息
Base URL
http://your-domain.com/api
协议
- HTTP/HTTPS
数据格式
- 请求:JSON
- 响应:JSON
字符编码
- UTF-8
版本
当前 API 版本:v1.0
版本控制通过 URL 路径实现:
/api/v1/articles
/api/v2/articles
认证方式
JWT Token 认证
CarefreeCMS 使用 JWT (JSON Web Token) 进行身份认证。
获取 Token
请求
POST /api/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "admin123"
}
响应
{
"code": 200,
"message": "登录成功",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"expire": 7200,
"user": {
"id": 1,
"username": "admin",
"email": "admin@example.com"
}
}
}
使用 Token
在后续请求中携带 Token:
方式一:Authorization Header(推荐)
GET /api/articles
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
方式二:Query Parameter
GET /api/articles?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
刷新 Token
Token 过期前可以刷新:
POST /api/auth/refresh
Authorization: Bearer OLD_TOKEN
Response:
{
"code": 200,
"data": {
"token": "NEW_TOKEN",
"expire": 7200
}
}
请求格式
HTTP 方法
| 方法 | 说明 | 示例 |
|---|---|---|
| GET | 获取资源 | GET /api/articles |
| POST | 创建资源 | POST /api/articles |
| PUT | 更新资源(全量) | PUT /api/articles/1 |
| PATCH | 更新资源(部分) | PATCH /api/articles/1 |
| DELETE | 删除资源 | DELETE /api/articles/1 |
请求头
Content-Type: application/json
Authorization: Bearer {token}
Accept: application/json
X-Requested-With: XMLHttpRequest
请求体
使用 JSON 格式:
{
"title": "文章标题",
"content": "文章内容",
"category_id": 1
}
查询参数
分页
GET /api/articles?page=1&page_size=20
筛选
GET /api/articles?category_id=1&status=1
排序
GET /api/articles?sort=create_time&order=desc
搜索
GET /api/articles?keyword=Vue
响应格式
成功响应
{
"code": 200,
"message": "操作成功",
"data": {
// 响应数据
},
"timestamp": 1640000000
}
分页响应
{
"code": 200,
"message": "获取成功",
"data": {
"list": [
// 数据列表
],
"total": 100,
"page": 1,
"page_size": 20,
"total_pages": 5
},
"timestamp": 1640000000
}
错误响应
{
"code": 400,
"message": "请求参数错误",
"errors": {
"title": ["标题不能为空"],
"content": ["内容不能为空"]
},
"timestamp": 1640000000
}
状态码
HTTP 状态码
| 状态码 | 说明 |
|---|---|
| 200 | 请求成功 |
| 201 | 创建成功 |
| 204 | 删除成功(无内容返回) |
| 400 | 请求参数错误 |
| 401 | 未认证或认证失败 |
| 403 | 无权限 |
| 404 | 资源不存在 |
| 422 | 验证失败 |
| 429 | 请求过于频繁 |
| 500 | 服务器内部错误 |
业务状态码
| 状态码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 参数错误 |
| 401 | 未登录 |
| 403 | 无权限 |
| 404 | 未找到 |
| 422 | 验证失败 |
| 500 | 服务器错误 |
| 10001 | Token 无效 |
| 10002 | Token 过期 |
| 10003 | 用户不存在 |
| 10004 | 密码错误 |
限流策略
为防止滥用,API 实施了请求频率限制。
限制规则
未认证用户
- 每分钟 30 次请求
- 超出后返回 429 状态码
已认证用户
- 每分钟 100 次请求
- VIP 用户无限制
限流信息
响应头包含限流信息:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000060
Limit: 限制次数Remaining: 剩余次数Reset: 重置时间(Unix时间戳)
错误处理
错误响应格式
{
"code": 422,
"message": "验证失败",
"errors": {
"field1": ["错误信息1", "错误信息2"],
"field2": ["错误信息1"]
},
"timestamp": 1640000000
}
常见错误
401 未授权
{
"code": 401,
"message": "请先登录"
}
403 无权限
{
"code": 403,
"message": "您没有权限执行此操作"
}
404 未找到
{
"code": 404,
"message": "请求的资源不存在"
}
422 验证失败
{
"code": 422,
"message": "数据验证失败",
"errors": {
"title": ["标题不能为空", "标题长度不能超过100个字符"],
"category_id": ["分类不存在"]
}
}
500 服务器错误
{
"code": 500,
"message": "服务器内部错误,请稍后重试"
}
批量操作
批量获取
GET /api/articles?ids=1,2,3,4,5
批量创建
POST /api/articles/batch
Content-Type: application/json
{
"articles": [
{"title": "文章1", "content": "内容1"},
{"title": "文章2", "content": "内容2"}
]
}
批量更新
PUT /api/articles/batch
Content-Type: application/json
{
"ids": [1, 2, 3],
"data": {
"status": 1
}
}
批量删除
DELETE /api/articles/batch
Content-Type: application/json
{
"ids": [1, 2, 3]
}
文件上传
单文件上传
POST /api/media/upload
Content-Type: multipart/form-data
Authorization: Bearer {token}
--boundary
Content-Disposition: form-data; name="file"; filename="image.jpg"
Content-Type: image/jpeg
[binary data]
--boundary--
响应
{
"code": 200,
"message": "上传成功",
"data": {
"id": 1,
"filename": "image.jpg",
"url": "https://example.com/uploads/2024/01/15/xxx.jpg",
"size": 102400,
"mime_type": "image/jpeg"
}
}
多文件上传
POST /api/media/upload/batch
Content-Type: multipart/form-data
--boundary
Content-Disposition: form-data; name="files[]"; filename="image1.jpg"
...
--boundary
Content-Disposition: form-data; name="files[]"; filename="image2.jpg"
...
--boundary--
Webhook
配置 Webhook
在后台配置 Webhook URL:
Webhook URL: https://your-domain.com/webhook
Secret: your_secret_key
Events: article.created, article.updated
Webhook 请求
系统会向配置的 URL 发送 POST 请求:
POST https://your-domain.com/webhook
Content-Type: application/json
X-Webhook-Signature: sha256=xxx
{
"event": "article.created",
"timestamp": 1640000000,
"data": {
"id": 1,
"title": "新文章标题",
"content": "文章内容"
}
}
验证签名
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'];
$expected = 'sha256=' . hash_hmac('sha256', $payload, $secret);
if (hash_equals($expected, $signature)) {
// 签名验证通过
}
使用示例
JavaScript (Axios)
// 安装: npm install axios
import axios from 'axios'
const api = axios.create({
baseURL: 'http://your-domain.com/api',
headers: {
'Content-Type': 'application/json',
},
})
// 添加请求拦截器
api.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// 登录
const login = async (username, password) => {
const res = await api.post('/auth/login', { username, password })
localStorage.setItem('token', res.data.data.token)
return res.data
}
// 获取文章列表
const getArticles = async (page = 1) => {
const res = await api.get('/articles', { params: { page } })
return res.data.data
}
// 创建文章
const createArticle = async (data) => {
const res = await api.post('/articles', data)
return res.data
}
PHP (cURL)
<?php
class ApiClient
{
private $baseUrl = 'http://your-domain.com/api';
private $token;
public function __construct($token = null)
{
$this->token = $token;
}
// 登录
public function login($username, $password)
{
$data = [
'username' => $username,
'password' => $password,
];
$response = $this->request('POST', '/auth/login', $data);
$this->token = $response['data']['token'];
return $response;
}
// 获取文章列表
public function getArticles($page = 1)
{
return $this->request('GET', "/articles?page={$page}");
}
// 创建文章
public function createArticle($data)
{
return $this->request('POST', '/articles', $data);
}
// 发送请求
private function request($method, $endpoint, $data = [])
{
$url = $this->baseUrl . $endpoint;
$ch = curl_init();
$headers = [
'Content-Type: application/json',
];
if ($this->token) {
$headers[] = "Authorization: Bearer {$this->token}";
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// 使用示例
$api = new ApiClient();
// 登录
$api->login('admin', 'admin123');
// 获取文章列表
$articles = $api->getArticles(1);
// 创建文章
$api->createArticle([
'title' => '新文章',
'content' => '文章内容',
'category_id' => 1,
]);
Python (requests)
# 安装: pip install requests
import requests
class ApiClient:
def __init__(self, base_url, token=None):
self.base_url = base_url
self.token = token
self.headers = {
'Content-Type': 'application/json',
}
def login(self, username, password):
"""登录"""
data = {
'username': username,
'password': password,
}
response = requests.post(
f'{self.base_url}/auth/login',
json=data,
headers=self.headers
)
result = response.json()
self.token = result['data']['token']
self.headers['Authorization'] = f'Bearer {self.token}'
return result
def get_articles(self, page=1):
"""获取文章列表"""
response = requests.get(
f'{self.base_url}/articles',
params={'page': page},
headers=self.headers
)
return response.json()
def create_article(self, data):
"""创建文章"""
response = requests.post(
f'{self.base_url}/articles',
json=data,
headers=self.headers
)
return response.json()
# 使用示例
api = ApiClient('http://your-domain.com/api')
# 登录
api.login('admin', 'admin123')
# 获取文章列表
articles = api.get_articles(page=1)
# 创建文章
api.create_article({
'title': '新文章',
'content': '文章内容',
'category_id': 1,
})
API 资源列表
核心接口
扩展接口
- 评论管理
- 专题管理
- 单页管理
- 友情链接
- 广告管理
- 幻灯片管理
最佳实践
使用 HTTPS
- 保护数据传输安全
- 防止中间人攻击
缓存 Token
- 避免频繁登录
- 实现自动刷新机制
错误处理
- 捕获所有错误
- 提供友好的错误提示
请求重试
- 网络错误时自动重试
- 设置合理的重试次数
日志记录
- 记录所有 API 调用
- 便于问题排查
更新日志
v1.0.0 (2024-01-15)
- 初始版本发布
- 完整的 RESTful API
- JWT 认证
- 文件上传
- Webhook 支持
获取帮助
- 📖 查看详细 API 文档
- 💬 加入开发者群:113572201
- 🐛 报告 Bug:GitHub Issues
- 📧 邮件咨询:dev@carefreecms.com
