PHP 入门教程
PHP RESTful API 设计
本教程共 65 篇 · 第 41 篇 · 更新于 2026-07-24 · 约 5 分钟阅读
PHPPHP8RESTful APIHTTP状态码路由JSONAPI设计
41. PHP RESTful API 设计
本节目标:理解 REST 架构原则,学会设计规范的 HTTP API,掌握状态码、JSON 响应和基础路由实现。
RESTful API 是现代 Web 服务的标准接口形式。前后端分离、移动端开发、第三方集成,都需要设计良好的 API。
41.1 什么是 REST
REST(Representational State Transfer)是一种架构风格,核心思想是:
- 资源(Resource):一切皆资源,如用户、文章、订单
- URI 定位:每个资源有唯一的地址,如
/users/123 - HTTP 方法表示操作:GET 查、POST 增、PUT 改、DELETE 删
- 无状态:每次请求包含所有必要信息,服务器不保存客户端状态
41.2 HTTP 方法对应 CRUD
| 方法 | 操作 | 示例 | 说明 |
|---|---|---|---|
GET | 读取 | GET /users | 获取用户列表 |
GET | 读取 | GET /users/123 | 获取 ID 为 123 的用户 |
POST | 创建 | POST /users | 创建新用户 |
PUT | 更新 | PUT /users/123 | 完整更新用户 123 |
PATCH | 部分更新 | PATCH /users/123 | 更新用户部分字段 |
DELETE | 删除 | DELETE /users/123 | 删除用户 123 |
Note
PUT要求提供资源的完整数据,PATCH只需提供要修改的字段。实际开发中两者常混用。
41.3 HTTP 状态码规范
API 应该返回恰当的状态码,让调用方清楚发生了什么:
| 状态码 | 含义 | 使用场景 |
|---|---|---|
200 OK | 成功 | GET、PUT、PATCH、DELETE 成功 |
201 Created | 已创建 | POST 创建资源成功 |
204 No Content | 无内容 | DELETE 成功,无需返回数据 |
400 Bad Request | 请求参数错误 | 参数缺失或格式不对 |
401 Unauthorized | 未认证 | 缺少登录凭证 |
403 Forbidden | 无权限 | 已登录但无权访问 |
404 Not Found | 资源不存在 | URL 或资源 ID 错误 |
422 Unprocessable | 验证失败 | 参数格式对但业务验证不通过 |
500 Server Error | 服务器错误 | 代码抛异常 |
41.4 统一的 JSON 响应格式
设计统一的响应结构,前端处理更方便:
<?php
function jsonResponse(int $code, mixed $data = null, string $message = ""): void {
http_response_code($code);
header("Content-Type: application/json; charset=utf-8");
echo json_encode([
"code" => $code,
"message" => $message,
"data" => $data,
"time" => date("Y-m-d H:i:s"),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 成功响应
jsonResponse(200, ["id" => 1, "name" => "张三"], "获取成功");
// 错误响应
jsonResponse(400, null, "用户名不能为空");
Tip始终返回 JSON,即使是错误情况。不要 HTML 和 JSON 混用,否则前端解析会出错。
41.5 手写路由实现
理解框架路由的底层原理:
<?php
// 简单的路由分发器
class Router {
private array $routes = [];
public function get(string $path, callable $handler): void {
$this->addRoute("GET", $path, $handler);
}
public function post(string $path, callable $handler): void {
$this->addRoute("POST", $path, $handler);
}
private function addRoute(string $method, string $path, callable $handler): void {
$this->routes[$method][$path] = $handler;
}
public function dispatch(): void {
$method = $_SERVER["REQUEST_METHOD"];
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if (isset($this->routes[$method][$uri])) {
call_user_func($this->routes[$method][$uri]);
} else {
http_response_code(404);
echo json_encode(["error" => "Not Found"]);
}
}
}
// 使用
$router = new Router();
$router->get("/api/users", function () {
echo json_encode(["users" => ["张三", "李四"]]);
});
$router->post("/api/users", function () {
$input = json_decode(file_get_contents("php://input"), true);
echo json_encode(["created" => true, "name" => $input["name"] ?? ""]);
});
$router->dispatch();
41.6 完整的用户 API 示例
<?php
require 'vendor/autoload.php';
header("Content-Type: application/json; charset=utf-8");
$method = $_SERVER["REQUEST_METHOD"];
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
// 模拟数据库
$users = [
1 => ["id" => 1, "name" => "张三", "email" => "zs@example.com"],
2 => ["id" => 2, "name" => "李四", "email" => "ls@example.com"],
];
// 路由匹配
if ($uri === "/api/users" && $method === "GET") {
echo json_encode(array_values($users));
} elseif (preg_match('/^\/api\/users\/(\d+)$/', $uri, $m) && $method === "GET") {
$id = (int) $m[1];
if (isset($users[$id])) {
echo json_encode($users[$id]);
} else {
http_response_code(404);
echo json_encode(["error" => "用户不存在"]);
}
} elseif ($uri === "/api/users" && $method === "POST") {
$input = json_decode(file_get_contents("php://input"), true);
if (empty($input["name"])) {
http_response_code(422);
echo json_encode(["error" => "姓名不能为空"]);
} else {
http_response_code(201);
echo json_encode(["id" => 3, "name" => $input["name"]]);
}
} else {
http_response_code(404);
echo json_encode(["error" => "接口不存在"]);
}
41.7 API 安全基础
- HTTPS 传输:生产环境必须启用,防止中间人攻击
- 认证机制:常用 API Key、JWT Token 或 OAuth
- 限流防刷:同一 IP 限制请求频率
- 参数校验:永远不要信任客户端输入
- CORS 控制:只允许可信域名访问
来源:参考了 runoob「PHP RESTful」、GitHub「php-the-right-way」及相关技术文档,改写后所得。