RESTful API是一种基于HTTP协议、符合REST架构风格的接口设计规范,通过不同的HTTP请求方法和URL路径来对应不同的资源操作,PHP作为常用的后端脚本语言,能够很方便地实现这类接口的搭建。

创建RESTful API的前期准备
首先需要准备基础的PHP运行环境,确保PHP版本在7.0及以上,同时需要开启JSON扩展,用于后续返回JSON格式的数据。如果是本地开发,可以安装集成环境如XAMPP或者WAMP,快速搭建PHP运行服务。
我们还需要明确要开发的API对应的资源,比如本文以用户资源为例,设计对应的接口操作:获取用户列表、获取单个用户、新增用户、更新用户、删除用户,分别对应不同的HTTP方法和URL路径。
定义接口路由规则
RESTful API的路由通过请求方法和URL路径共同确定,我们不需要依赖框架的路由组件,原生PHP可以通过解析请求方法和URL参数来实现路由分发。首先创建一个入口文件index.php,作为所有API请求的入口。
先获取当前的请求方法和请求的URI路径,示例代码如下:
<?php
// 获取请求方法
$requestMethod = $_SERVER['REQUEST_METHOD'];
// 获取请求URI,去除域名和入口文件前缀
$requestUri = $_SERVER['REQUEST_URI'];
// 假设入口文件是index.php,解析出实际的资源路径
$scriptName = $_SERVER['SCRIPT_NAME'];
$path = str_replace(dirname($scriptName), '', $requestUri);
$path = parse_url($path, PHP_URL_PATH);
$pathParts = explode('/', trim($path, '/'));
?>
处理不同的HTTP请求方法
根据RESTful规范,不同的操作对应不同的HTTP方法:GET用于查询资源,POST用于新增资源,PUT用于更新资源,DELETE用于删除资源。我们可以在入口文件中根据请求方法进行对应的逻辑处理。
处理GET请求
GET请求通常用于获取资源,比如获取用户列表或者单个用户的详情。如果是获取用户列表,URL路径可以设计为/users,如果是获取单个用户,路径为/users/1,其中1是用户ID。
示例处理逻辑如下:
<?php
// 模拟用户数据
$users = [
1 => ['id' => 1, 'name' => '张三', 'age' => 20],
2 => ['id' => 2, 'name' => '李四', 'age' => 22],
];
if ($requestMethod == 'GET') {
// 判断是获取列表还是单个用户
if (count($pathParts) == 1 && $pathParts[0] == 'users') {
// 返回用户列表
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 200, 'msg' => 'success', 'data' => array_values($users)]);
exit;
} elseif (count($pathParts) == 2 && $pathParts[0] == 'users' && is_numeric($pathParts[1])) {
// 返回单个用户
$userId = intval($pathParts[1]);
if (isset($users[$userId])) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 200, 'msg' => 'success', 'data' => $users[$userId]]);
} else {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 404, 'msg' => '用户不存在', 'data' => null]);
}
exit;
}
}
?>
处理POST请求
POST请求用于新增资源,比如新增用户,请求路径为/users,请求参数通过请求体传递,通常是JSON格式的数据。
处理POST请求的示例代码如下:
<?php
if ($requestMethod == 'POST') {
if (count($pathParts) == 1 && $pathParts[0] == 'users') {
// 获取请求体的JSON数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// 简单校验参数
if (!isset($data['name']) || !isset($data['age'])) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 400, 'msg' => '参数缺失', 'data' => null]);
exit;
}
// 模拟新增用户,实际项目中需要写入数据库
$newId = max(array_keys($users)) + 1;
$newUser = ['id' => $newId, 'name' => $data['name'], 'age' => $data['age']];
$users[$newId] = $newUser;
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 201, 'msg' => '新增成功', 'data' => $newUser]);
exit;
}
}
?>
处理PUT和DELETE请求
PUT请求用于更新资源,路径为/users/1,DELETE请求用于删除资源,路径同样为/users/1,处理逻辑和GET、POST类似,示例代码如下:
<?php
// 处理PUT请求
if ($requestMethod == 'PUT') {
if (count($pathParts) == 2 && $pathParts[0] == 'users' && is_numeric($pathParts[1])) {
$userId = intval($pathParts[1]);
if (!isset($users[$userId])) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 404, 'msg' => '用户不存在', 'data' => null]);
exit;
}
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// 更新用户信息
if (isset($data['name'])) {
$users[$userId]['name'] = $data['name'];
}
if (isset($data['age'])) {
$users[$userId]['age'] = $data['age'];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 200, 'msg' => '更新成功', 'data' => $users[$userId]]);
exit;
}
}
// 处理DELETE请求
if ($requestMethod == 'DELETE') {
if (count($pathParts) == 2 && $pathParts[0] == 'users' && is_numeric($pathParts[1])) {
$userId = intval($pathParts[1]);
if (!isset($users[$userId])) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 404, 'msg' => '用户不存在', 'data' => null]);
exit;
}
unset($users[$userId]);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['code' => 200, 'msg' => '删除成功', 'data' => null]);
exit;
}
}
?>
接口测试与优化
完成上述代码后,可以使用Postman或者curl工具测试接口是否正常工作。比如测试获取用户列表,发送GET请求到http://127.0.0.1/index.php/users,就能得到对应的JSON返回数据。
实际项目中还需要添加更多的优化项,比如请求参数的合法性校验、接口的身份认证、错误日志的记录、数据库的实际读写操作等,本文的示例是基础的原生实现,开发者可以根据实际需求扩展功能。
总结来说,用PHP创建RESTful API的核心是先明确资源和对应的操作,再通过解析请求方法和路径分发逻辑,最后返回标准的JSON格式数据,整个流程不需要复杂的框架也能快速实现。
PHPRESTful_APIAPI接口开发HTTP请求处理修改时间:2026-06-16 14:09:39