如何在30分钟内用PHP编写REST API:面向初学者
创建自己的REST API是每个Web开发者的重要一步。API允许您的应用程序与其他服务、移动应用或前端进行通信。本文将带您在30分钟内用纯PHP编写一个简单但功能完整的REST API。您将学习如何处理HTTP请求、使用JSON以及连接数据库。无需框架——只有纯PHP和清晰的示例。
什么是REST API,为什么需要它?
REST(表述性状态转移)是一种用于创建Web服务的架构风格。基于REST原则构建的API使用标准HTTP方法来操作资源:
- GET — 获取数据(例如,用户列表);
- POST — 创建新资源;
- PUT — 更新现有资源;
- DELETE — 删除资源。
在现代Web开发中,REST API被广泛使用:从移动应用到微服务。学会用PHP创建它后,您将能够快速将您的项目与任何客户端集成。
步骤1:配置项目结构
在编写代码之前,创建一个简单的文件结构。我们的API只需要几个文件:
index.php— 入口点,处理所有请求;.htaccess— 将所有请求重定向到index.php(如果使用Apache);config.php— 数据库连接配置(可选)。
在项目根文件夹中创建.htaccess文件:
RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ index.php [QSA,L]这段代码将所有不指向现有文件的请求重定向到index.php。现在,我们的API将处理任何URL,例如/api/users或/api/users/1。
步骤2:创建路由器和处理请求
打开index.php文件,编写基本的路由逻辑。我们将确定HTTP方法和URL,然后调用相应的函数。
<?phpheader("Content-Type: application/json; charset=UTF-8");header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");header("Access-Control-Allow-Headers: Content-Type, Authorization");
$method = $_SERVER['REQUEST_METHOD'];$request = explode('/', trim($_SERVER['PATH_INFO'] ?? '/', '/'));
// 最简单的路由器switch ($request[0] ?? '') { case 'users': handleUsers($method, $request); break; default: http_response_code(404); echo json_encode(["message" => "Route not found"]); break;}
function handleUsers($method, $request) { $id = $request[1] ?? null; switch ($method) { case 'GET': if ($id) { // 获取单个用户 echo json_encode(["message" => "Get user with id $id"]); } else { // 获取所有用户 echo json_encode(["message" => "Get all users"]); } break; case 'POST': $input = json_decode(file_get_contents("php://input"), true); echo json_encode(["message" => "Create user", "data" => $input]); break; case 'PUT': if ($id) { $input = json_decode(file_get_contents("php://input"), true); echo json_encode(["message" => "Update user with id $id", "data" => $input]); } else { http_response_code(400); echo json_encode(["message" => "ID is requ