实现RESTful API需基于HTTP方法与资源路径映射,使用PHP通过$_SERVER获取请求信息并解析路由,结合GET、POST、PUT、DELETE操作用户资源,配合JSON数据传输与状态码返回,构建轻量级接口。

实现一个RESTful API接口,核心在于正确理解HTTP方法与资源路径的映射关系,并通过路由机制将请求分发到对应的处理逻辑。PHP中可以通过简单的文件结构和路由解析来构建轻量级REST API,无需依赖框架也能高效完成。
RESTful设计原则简要
REST(Representational State Transfer)是一种基于HTTP协议的API设计风格。它强调使用标准的HTTP动词来操作资源:
GET:获取资源 POST:创建资源 PUT:更新资源(整体) PATCH:部分更新资源 DELETE:删除资源例如,对用户资源的操作可设计为:
GET /users → 获取用户列表 GET /users/1 → 获取ID为1的用户 POST /users → 创建新用户 PUT /users/1 → 更新ID为1的用户 DELETE /users/1 → 删除ID为1的用户PHP实现路由解析
在PHP中,所有请求可以统一由index.php入口文件处理,通过$_SERVER['REQUEST_URI']和$_SERVER['REQUEST_METHOD']获取路径和方法,再进行路由匹配。
立即学习“PHP免费学习笔记(深入)”;
示例代码如下:
代码小浣熊 代码小浣熊是基于商汤大语言模型的软件智能研发助手,覆盖软件需求分析、架构设计、代码编写、软件测试等环节
51 查看详情
// index.php$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);$uri = explode('/', trim($uri, '/'));$method = $_SERVER['REQUEST_METHOD'];// 假设路径格式为 /api/users 或 /api/users/1if ($uri[0] !== 'api') { http_response_code(404); echo json_encode(['error' => 'API endpoint not found']); exit;}$resource = $uri[1] ?? ''; // 资源名,如 users$id = $uri[2] ?? null; // ID(可选)// 模拟数据存储$users = [ 1 => ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'], 2 => ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com']];switch ($resource) { case 'users': switch ($method) { case 'GET': if ($id) { if (isset($users[$id])) { echo json_encode($users[$id]); } else { http_response_code(404); echo json_encode(['error' => 'User not found']); } } else { echo json_encode(array_values($users)); } break; case 'POST': $input = json_decode(file_get_contents('php://input'), true); $newId = max(array_keys($users)) + 1; $users[$newId] = [ 'id' => $newId, 'name' => $input['name'], 'email' => $input['email'] ]; http_response_code(201); echo json_encode($users[$newId]); break; case 'PUT': if (!$id || !isset($users[$id])) { http_response_code(404); echo json_encode(['error' => 'User not found']); break; } $input = json_decode(file_get_contents('php://input'), true); $users[$id]['name'] = $input['name'] ?? $users[$id]['name']; $users[$id]['email'] = $input['email'] ?? $users[$id]['email']; echo json_encode($users[$id]); break; case 'DELETE': if (!$id || !isset($users[$id])) { http_response_code(404); echo json_encode(['error' => 'User not found']); break; } unset($users[$id]); http_response_code(204); break; default: http_response_code(405); echo json_encode(['error' => 'Method not allowed']); } break; default: http_response_code(404); echo json_encode(['error' => 'Resource not found']);}登录后复制支持JSON输入与输出
现代API通常使用JSON格式传输数据。PHP需正确读取请求体中的JSON内容,并设置响应头为application/json。
关键点:
使用file_get_contents('php://input')读取原始POST/PUT数据 用json_decode()解析JSON字符串 输出前调用header('Content-Type: application/json')可在脚本开始处统一设置头信息:
header('Content-Type: application/json; charset=utf-8');header('Access-Control-Allow-Origin: *'); // 支持跨域(开发阶段)header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH');header('Access-Control-Allow-Headers: Content-Type');登录后复制改进方向与建议
上述实现适合学习和小型项目。实际开发中可考虑以下优化:
使用.htaccess重写URL,隐藏index.php 引入自动加载机制和类结构分离路由、控制器、模型 添加中间件处理认证、日志、输入验证 使用Composer管理依赖,集成PSR标准 结合Laravel、Slim等框架提升开发效率基本上就这些。掌握基础原理后,无论是手写路由还是使用框架,都能更清楚底层发生了什么。不复杂但容易忽略的是HTTP状态码的准确返回和错误信息的清晰表达。做好这些,你的API就已经足够专业。
以上就是PHP代码怎么实现RESTful API接口_PHP REST路由设计与实现的详细内容,更多请关注php中文网其它相关文章!


