search
HomeBackend DevelopmentPHP TutorialLearn to build RESTful APIs using PHP and MySQL

Learn to build RESTful APIs using PHP and MySQL

Jun 19, 2023 pm 04:06 PM
mysqlphprestful api

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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.