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

实现一个RESTful API接口,核心在于正确理解HTTP方法与资源路径的映射关系,并通过路由机制将请求分发到对应的处理逻辑。PHP中可以通过简单的文件结构和路由解析来构建轻量级REST API,无需依赖框架也能高效完成。
REST(Representational State Transfer)是一种基于HTTP协议的API设计风格。它强调使用标准的HTTP动词来操作资源:
例如,对用户资源的操作可设计为:
在PHP中,所有请求可以统一由index.php入口文件处理,通过$_SERVER['REQUEST_URI']和$_SERVER['REQUEST_METHOD']获取路径和方法,再进行路由匹配。
立即学习“PHP免费学习笔记(深入)”;
示例代码如下:
// index.php
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', trim($uri, '/'));
$method = $_SERVER['REQUEST_METHOD'];
// 假设路径格式为 /api/users 或 /api/users/1
if ($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']);
}
现代API通常使用JSON格式传输数据。PHP需正确读取请求体中的JSON内容,并设置响应头为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');
上述实现适合学习和小型项目。实际开发中可考虑以下优化:
基本上就这些。掌握基础原理后,无论是手写路由还是使用框架,都能更清楚底层发生了什么。不复杂但容易忽略的是HTTP状态码的准确返回和错误信息的清晰表达。做好这些,你的API就已经足够专业。
以上就是PHP代码怎么实现RESTful API接口_PHP REST路由设计与实现的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号