Home >Backend Development >PHP Problem >How to build an API server using PHP
With the rapid development of mobile, cloud computing, Internet of Things and other technologies, APIs have become an important way of data interaction between various applications and systems. In the field of web development, PHP, as a popular back-end language, provides many libraries and frameworks that facilitate API implementation. This article will introduce how to use PHP to build an API server and share the whole process from design to implementation.
1. Requirements analysis and design ideas
Before implementing the API server, we need to clarify the requirements and design ideas. This article implements a simple API server, and its requirements can be summarized as follows:
In order to achieve the above requirements, we can consider the following design ideas:
2. Build a development environment
Before building the API server, we need to prepare necessary development environments such as PHP and MySQL. You can choose to use an integrated development environment (IDE) such as PHPStorm, Eclipse, etc., or you can use a lightweight editor such as Visual Studio Code, Sublime Text, etc. This article takes PHPStorm as an example.
php -r "readfile('https://getcomposer.org/installer');" | php
After the installation is complete, move composer.phar to a globally available path, such as /usr/bin/composer.
3. Build the API server
With the above development environment, we can start to build the API server.
composer require slim/slim
or
composer require illuminate/routing illuminate/http
Note : If you choose to use the Lumen framework, you need to turn on the $app->withFacades() and $app->withEloquent() switches in the bootstrap/app.php file to use the Facade and Eloquent ORM functions provided by Lumen.
$app->get('/hello/{name}', function ($request, $response, $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->get('/users', 'UsersController:index'); $app->post('/users', 'UsersController:create');
Three routes are defined here:
$app->add(new JwtAuthMiddleware());
A JwtAuthMiddleware middleware is defined here to verify the token and permissions authorized by OAuth2.
namespace App\Controllers; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; use App\Models\User; class UsersController { public function index(Request $request, Response $response) { $users = User::all(); $response = $response->withJson($users); return $response; } public function create(Request $request, Response $response) { $data = $request->getParsedBody(); $user = new User; $user->name = $data['name']; $user->email = $data['email']; $user->password = password_hash($data['password'], PASSWORD_DEFAULT); $user->save(); $response = $response->withJson($user); return $response; } }
A UsersController controller is defined here, including the index and create methods, which correspond to /users GET and /users POST requests respectively. Use Eloquent ORM to operate the user data table (User::all() and $user->save()) and return a response in JSON format.
php -S localhost:8000 -t public
A built-in PHP Web server is started here, listening on port 8000. Access http://localhost:8000/hello/world in the browser. Under normal circumstances, the string "Hello, world" should be returned. When accessing http://localhost:8000/users, JSON format data of all users should be returned.
4. OAuth2 authorization
By default, the API server is insecure because anyone can access the interface and modify the data. To secure the API we can use OAuth2 authorization. OAuth2 is a standard authorization protocol that can authorize third-party applications to access protected resources of a specific user on a resource server without revealing the user name and password. In this article, we use Firebase's JWT framework to implement OAuth2 authorization.
composer require firebase/php-jwt
namespace App; use Firebase\JWT\JWT; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; use App\Models\User; class AuthorizationServer { private static $key = 'your_secret_key'; public static function getToken(Request $request, Response $response) { $data = $request->getParsedBody(); $user = User::where('email', $data['email'])->first(); if (!$user || !password_verify($data['password'], $user->password)) { return $response->withStatus(401)->withJson([ 'error' => 'Invalid email or password.' ]); } $now = time(); $payload = array( 'iat' => $now, 'exp' => $now + 3600, 'sub' => $user->id ); $jwt = JWT::encode($payload, self::$key); return $response->withJson([ 'access_token' => $jwt, 'token_type' => 'Bearer', 'expires_in' => 3600 ]); } public static function authenticate(Request $request) { $jwt = isset($request->getHeader('Authorization')[0]) ? explode(' ', $request->getHeader('Authorization')[0])[1] : null; if (!$jwt) { throw new Exception('Unauthorized.'); } try { $decoded = JWT::decode($jwt, self::$key, array('HS256')); $user = User::find($decoded->sub); if (!$user) { throw new Exception('Unauthorized.'); } return $user; } catch (Exception $e) { throw new Exception('Unauthorized.'); } } }
An AuthorizationServer authorization server is defined here, including two methods:
这里使用了JWT加密框架,将用户信息存储在token中,并使用HS256算法加密。
namespace App\Middlewares; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; use App\AuthorizationServer; class JwtAuthMiddleware { public function __invoke(Request $request, Response $response, $next) { try { $user = AuthorizationServer::authenticate($request); $request = $request->withAttribute('user', $user); return $next($request, $response); } catch (Exception $e) { return $response->withStatus(401)->withJson([ 'error' => $e->getMessage() ]); } } }
这里定义了一个JwtAuthMiddleware中间件,用户验证客户端请求的access token的有效性,并在后面的控制器中通过$request->getAttribute('user')获取到用户对象。
$app->post('/auth/token', 'AuthorizationServer:getToken'); $app->group('', function () use ($app) { $app->get('/users/@id', 'UsersController:getUser'); $app->put('/users/@id', 'UsersController:updateUser'); $app->delete('/users/@id', 'UsersController:deleteUser'); })->add(new JwtAuthMiddleware());
这里定义了一个/auth/token路由,用于获取访问令牌。另外,对于需要OAuth2授权的路由(getUser、updateUser和deleteUser),使用$app->group()方法包裹其中,并添加JwtAuthMiddleware中间件。
五、总结
本文介绍了如何使用PHP搭建API服务器,基于Slim或Lumen框架,解析URL参数、返回JSON格式的数据,并使用OAuth2框架保护API的安全性。使用这种方式搭建API服务器,可以快速、高效地开发出各种类型的RESTful API。但是,具体实现还需要根据实际需求进行适当调整和优化。
The above is the detailed content of How to build an API server using PHP. For more information, please follow other related articles on the PHP Chinese website!