Home  >  Article  >  Backend Development  >  Learn to build RESTful APIs using PHP and MySQL

Learn to build RESTful APIs using PHP and MySQL

PHPz
PHPzOriginal
2023-06-19 16:06:46759browse

With the development of web development, RESTful API has become one of the standards for modern web applications. Compared with traditional APIs, RESTful APIs are more flexible and scalable. PHP and MySQL, as widely used web development tools, can also be used to build RESTful APIs. This article will introduce in detail how to build a RESTful API using PHP and MySQL, and provide code examples and considerations.

1. Introduction to RESTful API

RESTful API is a Web API design form based on HTTP protocol and standard data format. It usually uses HTTP verbs (GET, POST, PUT, DELETE, etc.) to operate on resources, and uses HTTP status codes to represent the operation results. The design principles of RESTful API include resources, representational state transfer, unified interface, self-containment and hypermedia.

2. Use PHP and MySQL to build RESTful API

  1. Install and configure PHP and MySQL

First you need to install and configure PHP and MySQL, which is not covered here Again. After the installation is complete, you can use the phpinfo function to verify whether PHP is working properly, or create a test database in MySQL to verify whether MySQL is working properly.

  1. Create the basic structure of the RESTful API

Next, you need to create the basic structure of the RESTful API. The first is the database connection, using the following code:

<?php
 
//数据库连接参数 
define('DB_HOST', 'localhost'); 
define('DB_USER', 'root'); 
define('DB_PASS', ''); 
define('DB_NAME', 'test');
 
//建立数据库连接 
function connect() {
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if(mysqli_connect_errno()) {
        die("Database connection failed: " . mysqli_connect_error());
    }
    return $mysqli;
}
 
//关闭数据库连接 
function disconnect($mysqli) {
    $mysqli -> close();
}
 
?>

It should be noted that the object-oriented mysqli connection is used here instead of the traditional mysql connection method.

Next, you need to create a basic RESTful API class, which defines the behavior of HTTP requests and responses. Four HTTP verbs are defined here: GET, POST, PUT and DELETE. Use the following code:

<?php
 
require_once('db_connect.php');
 
class Rest {
 
    protected $request;
    protected $mysqli;
    protected $method;
    protected $args;
    protected $resource = '';
    protected $statusCodes = array(
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        204 => 'No Content',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        403 => 'Forbidden',
        404 => 'Not Found',
        406 => 'Not Acceptable',
        500 => 'Internal Server Error'
    );
 
    public function __construct() {
        $this -> mysqli = connect();
        $this -> request = explode('/', trim($_SERVER['PATH_INFO'], '/'));
        $this -> method = $_SERVER['REQUEST_METHOD'];
        $this -> args = $_SERVER['QUERY_STRING'];
        $this -> resource = array_shift($this -> request);
    }
 
    public function processRequest() {
 
        switch($this -> method) {
            case 'POST':
                $response = $this -> create();
                break;
            case 'PUT':
                $response = $this -> update();
                break;
            case 'DELETE':
                $response = $this -> delete();
                break;
            case 'GET':
            default:
                $response = $this -> read();
                break;
        }
 
        header('HTTP/1.1 ' . $this -> statusCodes[$response['status']]);
        header('Content-Type: application/json; charset=utf-8');
 
        return json_encode($response['data']);
    }
 
    protected function create() {}
    protected function read() {}
    protected function update() {}
    protected function delete() {}
 
}
 
?>

The constructor of this class will parse the method, path and parameters in the HTTP request and save them in the object properties. Then call the corresponding method according to the HTTP method to process the request.

  1. Implement CRUD operations of RESTful API

Next, you need to implement CRUD operations in the RESTful API class. Taking a user as an example, use the following code:

class UserAPI extends Rest {
 
    public function create() {
        $data = json_decode(file_get_contents("php://input"), true);
        $username = $data['username'];
        $password = $data['password'];
        $email = $data['email'];
 
        if(!empty($username) && !empty($password) && !empty($email)) {
            $stmt = $this -> mysqli -> prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
            $stmt -> bind_param("sss", $username, $password, $email);
            $stmt -> execute();
            $stmt -> close();
            $response['status'] = 201;
            $response['data'] = "User created successfully.";
        } else {
            $response['status'] = 400;
            $response['data'] = "Invalid parameters.";
        }
 
        return $response;
    }
 
    public function read() {
        $id = array_shift($this -> request);
        if(empty($id)) {
            $result = $this -> mysqli -> query("SELECT * FROM users");
            while($row = $result -> fetch_assoc()) {
                $data[] = $row;
            }
            $response['status'] = 200;
            $response['data'] = $data;
        } else {
            $result = $this -> mysqli -> query("SELECT * FROM users WHERE id = $id");
            if($result -> num_rows == 1) {
                $response['status'] = 200;
                $response['data'] = $result -> fetch_assoc();
            } else {
                $response['status'] = 404;
                $response['data'] = "User not found.";
            }
        }
        return $response;
    }
 
    public function update() {
        $id = array_shift($this -> request);
        $data = json_decode(file_get_contents("php://input"), true);
        $username = $data['username'];
        $password = $data['password'];
        $email = $data['email'];
 
        if(!empty($username) && !empty($password) && !empty($email)) {
            $stmt = $this -> mysqli -> prepare("UPDATE users SET username=?, password=?, email=? WHERE id=?");
            $stmt -> bind_param("sssi", $username, $password, $email, $id);
            $stmt -> execute();
            $stmt -> close();
            $response['status'] = 200;
            $response['data'] = "User updated successfully.";
        } else {
            $response['status'] = 400;
            $response['data'] = "Invalid parameters.";
        }
 
        return $response;
    }
 
    public function delete() {
        $id = array_shift($this -> request);
        $result = $this -> mysqli -> query("SELECT * FROM users WHERE id = $id");
        if($result -> num_rows == 1) {
            $this -> mysqli -> query("DELETE FROM users WHERE id = $id");
            $response['status'] = 200;
            $response['data'] = "User deleted successfully.";
        } else {
            $response['status'] = 404;
            $response['data'] = "User not found.";
        }
        return $response;
    }
 
}

A UserAPI class is defined here and implements the create, read, update and delete methods. For POST requests, the Json data will be parsed into usernames, passwords and email addresses, and inserted into the users table; for GET requests, if the URL contains the id parameter, the corresponding user information will be returned, otherwise all user information will be returned; for PUT request, parse Json data into user name, password and email address, and update the corresponding user's information; for DELETE request, delete the corresponding user according to the id parameter in the URL.

  1. Using RESTful API

After creating the RESTful API, you can use tools such as curl to test whether the API is working properly. Use the following curl command to create a user to the RESTful API:

curl -H "Content-Type: application/json" -X POST -d '{
    "username":"testuser",
    "password":"testpassword",
    "email":"testuser@example.com"
}' http://localhost/user

Use the following curl command to return all users:

curl http://localhost/user

Use the following curl command to update user information:

curl -H "Content-Type:application/json" -X PUT -d '{
    "username":"newusername",
    "password":"newpassword",
    "email":"newusername@example.com"
}' http://localhost/user/1

Use the following curl Command to delete users:

curl -X DELETE http://localhost/user/1

3. Notes

You need to pay attention to the following points when building a RESTful API:

  1. Database security. RESTful APIs usually need to interact with databases, and there may be security issues such as SQL injection. Parameterized queries and other methods need to be used to ensure data security.
  2. Cross-domain issues. RESTful API may be called by applications under different domain names, causing cross-domain problems. Access-Control-Allow-Origin and other related HTTP headers need to be set.
  3. API version control. Version control needs to be considered when designing RESTful APIs to avoid affecting existing APIs.
  4. HTTP status code. The return value of the RESTful API needs to correctly use the HTTP status code to represent the result of the request.

4. Summary

This article introduces how to use PHP and MySQL to build a RESTful API, and provides code examples and precautions. The advantages of RESTful API are flexibility, scalability, easy maintenance, etc. It is an indispensable part of web development. When using RESTful APIs, you need to pay attention to issues such as security, cross-domain issues, version control, and HTTP status codes.

The above is the detailed content of Learn to build RESTful APIs using PHP and MySQL. 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