Home Backend Development PHP Problem How to build an API server using PHP

How to build an API server using PHP

Apr 21, 2023 am 09:06 AM

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
Copy after login

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
Copy after login

or

composer require illuminate/routing illuminate/http
Copy after login

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');
Copy after login

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());
Copy after login

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;
    }
    
}
Copy after login

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
Copy after login

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
Copy after login
  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.');
        }
    }
    
}
Copy after login

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()
            ]);
        }
    }
    
}
Copy after login

这里定义了一个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());
Copy after login

这里定义了一个/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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP XSS Prevention: How to protect against XSS. PHP XSS Prevention: How to protect against XSS. Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

ACID vs BASE Database: Differences and when to use each. ACID vs BASE Database: Differences and when to use each. Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Password Hashing: password_hash and password_verify. PHP Password Hashing: password_hash and password_verify. Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

PHP Interface vs Abstract Class: When to use each. PHP Interface vs Abstract Class: When to use each. Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles