Home  >  Article  >  Backend Development  >  How to build an API server using PHP

How to build an API server using PHP

PHPz
PHPzOriginal
2023-04-21 09:06:571588browse

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:

  1. supports HTTP protocol and can handle GET, POST and other requests;
  2. can parse URL parameters and implement RESTful API;
  3. can return data in JSON format;
  4. supports OAuth2 authorization to protect the security of the API.

In order to achieve the above requirements, we can consider the following design ideas:

  1. Use the PHP extension package Slim or Lumen to build the API server, which provides good routing, Structured programming tools such as middleware and controllers and rich plug-in mechanisms;
  2. Parse URL parameters in routing and use the OAuth2 framework to protect API security;
  3. Get in the controller Request parameters, call the model to access the database or other data sources, and output data in JSON format.

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.

  1. Install PHPStorm and PHP environment: Download PHPStorm. During the installation process, you will be prompted to install the PHP environment. PHP will be installed by default, or you can choose the installation path yourself. After the installation is complete, run PHPStorm, open Preferences, and add the PHP interpreter in Languages ​​& Frameworks > PHP.
  2. Install MySQL: Download and install MySQL, create and configure the database.
  3. Install Composer: Composer is a dependency manager for PHP, which can greatly simplify PHP development work. Execute the following command on the command line to install Composer:
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.

  1. Create a project: Create a new PHP project in PHPStorm and use Composer to install the Slim or Lumen framework:
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.

  1. Creating routes: Creating routes and middleware is easy in the Slim or Lumen framework. Create the routes.php file in the root directory, for example:
$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:

  • /hello/{name}: accepts a name parameter, Returns the string of "Hello, name";
  • /users: GET request, calls the index method of UsersController, returns all user data;
  • /users: POST request, calls the create method of UsersController , create a new user record.
  1. Create middleware: Adding middleware to routing can achieve some preprocessing, filtering, authorization and other functions. Create the middleware.php file in the root directory, for example:
$app->add(new JwtAuthMiddleware());

A JwtAuthMiddleware middleware is defined here to verify the token and permissions authorized by OAuth2.

  1. Create a controller: Create a controller file in the root directory, such as UsersController.php, to implement all methods defined by the route. The code structure of the controller can refer to the following example:
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.

  1. Run the API server: Enter the project directory on the command line and execute the following command:
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.

  1. Install the Firebase JWT framework: Use Composer to install the Firebase JWT framework:
composer require firebase/php-jwt
  1. Create the authorization server: Create the AuthorizationServer.php file in the root directory, for example:
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:

  • getToken:接受客户端传递的email和password,生成access token并返回给客户端;
  • authenticate:接受客户端传递的access token,验证并返回用户对象。

这里使用了JWT加密框架,将用户信息存储在token中,并使用HS256算法加密。

  1. 创建中间件:在根目录下创建中间件文件JwtAuthMiddleware.php,例如:
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')获取到用户对象。

  1. 更新路由:在路由中加入OAuth2授权相关的路由和中间件。在routes.php文件中增加以下代码:
$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn