首页 / PHP 入门教程 / PHP RESTful API 设计

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)是一种架构风格,核心思想是:

  1. 资源(Resource):一切皆资源,如用户、文章、订单
  2. URI 定位:每个资源有唯一的地址,如 /users/123
  3. HTTP 方法表示操作:GET 查、POST 增、PUT 改、DELETE 删
  4. 无状态:每次请求包含所有必要信息,服务器不保存客户端状态

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 安全基础

  1. HTTPS 传输:生产环境必须启用,防止中间人攻击
  2. 认证机制:常用 API Key、JWT Token 或 OAuth
  3. 限流防刷:同一 IP 限制请求频率
  4. 参数校验:永远不要信任客户端输入
  5. CORS 控制:只允许可信域名访问

来源:参考了 runoob「PHP RESTful」、GitHub「php-the-right-way」及相关技术文档,改写后所得。