Hurry Up! Refer new customers to Codentheme and receive  10%  of their each purchase. Become an affiliate now
RESTful APIs in PHP: A Hands-on Approach for Beginners

RESTful APIs in PHP: A Hands-on Approach for Beginners

RESTful APIs, or Representational State Transfer APIs.

RESTful APIs are a set of architectural principles and conventions. It facilitates communication between different systems over the internet. They are crucial to modern web development as they enable developers to build modular, scalable, and interoperable applications.

The importance of RESTful APIs in modern web development cannot be overstated. Because it allows developers to build modular, scalable, and interoperable applications. 

You can see here some advantages of building RESTful APIs using PHP and MySQL. 

  1. PHP’s Simplicity and Ease of Use. PHP is a popular server-side scripting language known for its simplicity and ease of use. The low learning curve makes it accessible to developers with varying levels of experience. PHP offers a rich set of built-in functions and a huge community-driven ecosystem, making it a viable choice for API development. 
  2. MySQL’s Efficient Data Storage and Retrieval. MySQL is an open-source relational database management system that provides efficient storage and retrieval of data. It is widely used and highly optimized for handling large amounts of structured data. MySQL supports robust querying capabilities and offers features like indexing and caching, which contribute to improved API performance.
  3. Compatibility and Integration. Both PHP and MySQL are widely supported technologies in the world of web development. They are compatible with a wide range of operating systems and web servers, allowing seamless integration into your existing infrastructure. In addition, numerous libraries and frameworks are available that facilitate API development in PHP and allow easy interaction with MySQL databases.  
  4. Scalability and Performance. PHP and MySQL offer scalability options that allow your API to handle increased traffic and increased data demands. Proper database indexing, caching strategies, and code optimizations can ensure high performance and responsiveness of your APIs even under heavy load. 
  5. Community Support and Resources. PHP and MySQL have large and active developer communities with extensive resources, tutorials and documentation available. This makes it easier to find help, learn best practices, and leverage your existing knowledge to build robust and secure RESTful APIs.  

The Basic File Structure for a REST API.

The basic file structure of a REST API refers to the organization and layout of files and directories within an API project. It provides a logical structure to store various components such as controllers, models, routes and other necessary files.

Here is an example of a basic file structure for the REST API. 


- app
  - controllers
    - UserController.php
    - ProductController.php
  - models
    - User.php
    - Product.php
  - routes
    - api.php
  - config.php
  - index.php

Let’s break down each component:

  1. app/: This is the root directory of your API project.
  2. controllers/: The controllers directory contains files that handle different API endpoints. For example, UserController.php might handle user-related endpoints, and ProductController.php might handle product-related endpoints.
  3. models/: The models directory holds files that define the data models or entities in your API. These files, such as User.php and Product.php, typically include functions for interacting with the corresponding database tables.
  4. routes/: The routes directory stores files responsible for defining the API routes and their associated controller methods. For instance, api.php might define the routes for various API endpoints.
  5. config.php: The config.php file contains configuration settings for your API, such as database credentials or other environment-specific configurations.
  6. index.php: The index.php file serves as the entry point for your API. It handles incoming requests, performs routing, and dispatches the request to the appropriate controller method.

This file structure provides a foundation for organizing your API code, separating concerns, and promoting maintainability. It’s important to note that this is a simplified example, and the actual structure may vary based on the framework or libraries you use.

As your API grows, you can extend the file structure by adding directories for middleware, helpers, database migrations, or tests, depending on your project’s requirements.


We will walk you through examples that showcase the functionality of a REST API. 

Learn how to interact with APIs and manipulate data using HTTP requests such as GET, POST, PUT, and DELETE.


Ready to get started?

Building a Simple REST API with PHP & MySQL.

Setting Up the Environment.

To set up your development environment for building a RESTful API with PHP and MySQL, you’ll need to install PHP, MySQL, and a web server like Apache or Nginx. These components are essential for creating and running your API, and they require installation and configuration before you can start development.

Designing the Database.

Designing a proper database schema for your RESTful API is crucial as it ensures efficient storage and retrieval of data while maintaining data integrity. A well-designed database schema helps organize and structure your data in a logical manner, enabling smooth interaction with your API.

Here are the essential components of a RESTful API database design-

  1. Tables: Tables represent entities or resources in your API. Each table corresponds to a specific type of data you want to store. For example, you might have tables for users, products, orders, or any other relevant entities.
  2. Relationships: Relationships define how different tables are related to each other. There are three common types of relationships: one-to-one, one-to-many, and many-to-many. These relationships help establish connections and dependencies between entities.
  3. Primary Keys: Primary keys are unique identifiers for each record in a table. They ensure the uniqueness of data and enable efficient data retrieval. Typically, primary keys are auto-incrementing integers or unique alphanumeric values.
  4. Foreign Keys: Foreign keys are used to establish relationships between tables. They refer to the primary key of another table, creating a link between the two tables. Foreign keys maintain data consistency and enforce referential integrity.

To illustrate the process of creating tables and establishing relationships using SQL statements, consider a simple e-commerce API example. In this scenario, we have two tables:

One to store user information and the other to manage product data. 

  • Creating the “users” table.
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL,
  password VARCHAR(255) NOT NULL
);
  • Creating the “products” table.
CREATE TABLE products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  description TEXT
);
  • Establishing a one-to-many relationship between the “users” and “products” tables.
ALTER TABLE products ADD COLUMN user_id INT NOT NULL;
ALTER TABLE products ADD CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(id);

Above, we created two tables.

“user” and “product”. The Users table contains ID, Name, Email, and Password columns. The Products table contains columns for ID, Name, Price, Description, and User ID. The user_id column of the products table establishes a foreign key relationship with the id column of the users table.

You can design the database schema for your RESTful API by following these steps to customize the table and column names. 

Remember to analyze your API requirements and relationships between entities to create an effective and efficient database design.  

Creating the PHP Backend.

The basic structure and principles of a RESTful API revolve around using HTTP methods (GET, POST, PUT, DELETE) to perform different operations on resources.

Here’s an explanation of the key elements:

  1. HTTP Methods: RESTful APIs utilize the HTTP methods to interact with resources. Each method has a specific purpose:
    • GET: Retrieves data from a resource.
    • POST: Creates a new resource.
    • PUT: Updates an existing resource.
    • DELETE: Removes a resource.
  2. Entry Point: Your RESTful API needs a main PHP file that serves as the entry point for handling API requests and generating responses. This file will typically receive the incoming requests, extract relevant information, and invoke the appropriate functions to process the requests.

To better understand the HTTP methods, let’s create a simple PHP file named ‘api.php‘. This file serves as an example showing how to handle different types of requests such as GET, POST, PUT, and DELETE. 

<?php
// Retrieve the user's information based on the request parameters
function getUser($userId) {
  // Perform database query or any other logic to fetch the user's information
  // Replace this with your actual code
  $user = [
    'id' => $userId,
    'name' => 'John Doe',
    'email' => 'johndoe@example.com'
  ];

  return $user;
}

// Handle GET request to fetch user's information
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  // Extract the user ID from the query parameters
  $userId = $_GET['id'];

  // Call the getUser function to fetch the user's information
  $user = getUser($userId);

  // Check if the user was found
  if ($user) {
    // Set the response headers to indicate JSON content
    header('Content-Type: application/json');

    // Convert the user's information to JSON format
    $userJson = json_encode($user);

    // Return the JSON response
    echo $userJson;
  } else {
    // Return a 404 Not Found response if the user was not found
    http_response_code(404);
    echo 'User not found';
  }
}

// Handle POST request to create a new user
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Extract the user's information from the request body
  $data = json_decode(file_get_contents('php://input'), true);

  // Process the user's information and create a new user
  // Replace this with your actual code

  // Set the response headers to indicate JSON content
  header('Content-Type: application/json');

  // Return a success message or the created user's information
  echo json_encode(['message' => 'User created']);
}

// Handle PUT request to update a user's information
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
  // Extract the user ID from the query parameters
  $userId = $_GET['id'];

  // Extract the user's updated information from the request body
  $data = json_decode(file_get_contents('php://input'), true);

  // Process the user's updated information and update the user
  // Replace this with your actual code

  // Set the response headers to indicate JSON content
  header('Content-Type: application/json');

  // Return a success message or the updated user's information
  echo json_encode(['message' => 'User updated']);
}

// Handle DELETE request to delete a user
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
  // Extract the user ID from the query parameters
  $userId = $_GET['id'];

  // Process the user deletion logic
  // Replace this with your actual code

  // Set the response headers to indicate JSON content
  header('Content-Type: application/json');

  // Return a success message or the deleted user's information
  echo json_encode(['message' => 'User deleted']);
}
?>

In the provided example, the file “api.php” consists of functions responsible for handling different types of requests: GET, POST, PUT, and DELETE.

For a GET request, the function retrieves a user’s information using the user ID provided.

A POST request creates a new user by extracting the necessary data from the request body.

The PUT request updates an existing user’s information by utilizing the user ID and the updated data obtained from the request body.

Lastly, the DELETE request deletes a user identified by the specified user ID.

Remember to modify the logic within each function according to your specific API requirements, such as executing or validating database operations.

Additionally, ensure that you set the appropriate response headers and format the response in JSON.

By following these steps and extending the implementation to handle other resources, you can create a PHP backend for your RESTful API.

Handling API Requests.

When handling different types of API requests, the role of HTTP headers, query parameters, and request bodies is crucial in API communication:

HTTP Headers: HTTP headers provide additional information about the request or response. They can be used to pass authentication tokens, specify the content type, enable caching, and more.

To extract data from the request headers in PHP, you can use the $_SERVER superglobal array.

For example, to extract an authentication token from the request header:

$authToken = $_SERVER['HTTP_AUTHORIZATION'];

Query Parameters: Query parameters are used to send additional data in the URL. They are typically used for filtering, sorting, or paginating resources.

To extract data from the query parameters in PHP, you can use the $_GET superglobal array.

For example, to extract a user_id parameter from the URL:

$userId = $_GET['user_id'];

Request Body: The request body contains the data sent by the client, usually in JSON or form-urlencoded format. It is commonly used for creating or updating resources.

To extract data from the request body in PHP, you can use the file_get_contents function to retrieve the raw body, and then use json_decode to parse it as JSON. For example, assuming the request body is in JSON format:

$requestBody = file_get_contents('php://input');
$data = json_decode($requestBody, true);

To validate and sanitize user input, you can use PHP functions like filter_input and prepared statements:

// Validate and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->execute([$username, $email]);

In the above example, filter_input is used to validate and sanitize the username and email inputs, while prepared statements with placeholders (?) are used to safely interact with the database, preventing SQL injection attacks.

Interacting with the MySQL Database.

To establish a connection with the MySQL database using PHP, you can use either the mysqli or PDO extension.

Using mysqli extension.

  • Create a new mysqli object with the database credentials.
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
$mysqli = new mysqli($host, $username, $password, $database);

  • Check if the connection was successful.
if ($mysqli->connect_errno) {
  die('Failed to connect to MySQL: ' . $mysqli->connect_error);
}

Using PDO extension.

  • Create a new PDO object with the database credentials
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
$dsn = "mysql:host=$host;dbname=$database";
try {
  $pdo = new PDO($dsn, $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  die('Failed to connect to MySQL: ' . $e->getMessage());
}

Once the connection is established, you can perform CRUD operations on the MySQL database using SQL queries. Here are some examples:

Retrieving data:

  • Fetch all products from the database using mysqli:
$sql = 'SELECT * FROM products';
$result = $mysqli->query($sql);
$products = $result->fetch_all(MYSQLI_ASSOC);
  • Fetch all products from the database using PDO:
$sql = 'SELECT * FROM products';
$stmt = $pdo->query($sql);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

Inserting data:

  • Insert a new user into the database using mysqli:
$username = 'JohnDoe';
$email = 'johndoe@example.com';
$sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')";
$result = $mysqli->query($sql);
  • Insert a new user into the database using PDO:
$username = 'JohnDoe';
$email = 'johndoe@example.com';
$sql = "INSERT INTO users (username, email) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$username, $email]);

Updating data:

  • Update a user’s information using mysqli:
$userId = 1;
$email = 'newemail@example.com';
$sql = "UPDATE users SET email='$email' WHERE id=$userId";
$result = $mysqli->query($sql);
  • Update a user’s information using PDO:
$userId = 1;
$email = 'newemail@example.com';
$sql = "UPDATE users SET email=? WHERE id=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$email, $userId]);

Deleting data:

  • Delete a user from the database using mysqli:
$userId = 1;
$sql = "DELETE FROM users WHERE id=$userId";
$result = $mysqli->query($sql);
  • Delete a user from the database using PDO:
$userId = 1;
$sql = "DELETE FROM users WHERE id=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId]);

Remember to modify the SQL queries and table/column names based on your specific database schema.

Implementing Authentication and Authorization.

Securing your API using authentication and authorization is crucial for protecting sensitive data and controlling access to protected resources.

Authentication verifies the identity of users, ensuring they are who they claim to be. Authorization, on the other hand, determines what actions and resources a user is allowed to access based on their authenticated identity.

To implement basic authentication using PHP and MySQL, you can follow these steps:

  1. Receive the username and password from the client in the API request.
  2. Retrieve the hashed password for the provided username from the database.
  3. Use PHP’s password_verify function to compare the provided password with the hashed password.
  4. If the passwords match, authenticate the user and grant access to the protected resources.

Here’s an example implementation:

// Receive username and password from the API request
$username = $_POST['username'];
$password = $_POST['password'];

// Retrieve the hashed password for the provided username from the database
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch();

// Verify the provided password with the hashed password
if ($result && password_verify($password, $result['password'])) {
  // Authentication successful
  // Grant access to protected resources
} else {
  // Authentication failed
  // Return an error response or deny access
}

Token-based authentication provides a stateless approach to authentication, where a token is generated and used for subsequent API requests. This eliminates the need to authenticate with username and password for every request. JSON Web Tokens (JWTs) are a popular token-based authentication mechanism.

To implement token-based authentication using JWTs, you can follow these steps:

  1. When the user logs in successfully, generate a JWT containing the user’s information.
  2. Sign the JWT using a secret key to prevent tampering.
  3. Include the JWT in the response to the client.
  4. For subsequent API requests, the client sends the JWT in the Authorization header.
  5. On the server, validate the JWT, ensuring it has not been tampered with and is not expired.
  6. If the validation is successful, grant access to the protected resources.

Here’s an example implementation:

use Firebase\JWT\JWT;

// Generate a JWT when the user logs in successfully
$payload = array(
  "user_id" => $user_id,
  "username" => $username
);
$jwt = JWT::encode($payload, 'secret_key');

// Return the JWT to the client
$response = array(
  "token" => $jwt
);
echo json_encode($response);

// Validate the JWT on subsequent requests
$jwt = $_SERVER['HTTP_AUTHORIZATION'];
$secret_key = 'secret_key';

try {
  $decoded = JWT::decode($jwt, $secret_key, array('HS256'));
  // Authentication successful
  // Grant access to protected resources
} catch (Exception $e) {
  // Authentication failed
  // Return an error response or deny access
}

By implementing authentication and authorization, you can ensure that only authenticated and authorized users can access your API’s protected resources.

Basic authentication validates the username and password, while token-based authentication using JWTs provides a secure and stateless approach for subsequent requests.

Handling Errors and Exception Handling.

Handling errors and exceptions in a RESTful API is essential for providing a smooth and user-friendly experience. When an error occurs, it’s important to communicate the issue clearly to clients by providing meaningful error messages. This helps clients understand what went wrong and how to resolve the issue.

Common HTTP error codes play a crucial role in indicating the nature of the error. Here are a few examples:

  • 404 Not Found: Use this status code when the requested resource is not found. For example, if a client requests a non-existent endpoint or a specific resource that does not exist.
  • 400 Bad Request: This status code indicates that the server cannot process the client’s request due to malformed syntax or invalid parameters. Use it when the client sends an invalid request that cannot be understood.
  • 401 Unauthorized: Use this status code when the client is not authenticated and trying to access a protected resource.
  • 403 Forbidden: If the client is authenticated but not authorized to access the requested resource, return this status code.
  • 500 Internal Server Error: This status code indicates an unexpected error on the server side. It should be used for generic server errors.

To handle and format error responses in a RESTful API, you can follow these steps:

  1. Determine the appropriate HTTP status code based on the error scenario.
  2. Set the HTTP status code using PHP’s header() function.
  3. Create an error response in JSON format, including an error message and, if necessary, additional details or error codes.
  4. Return the error response to the client.

Here’s an example implementation:

// Set the appropriate HTTP status code
http_response_code(404);

// Create an error response in JSON format
$errorResponse = array(
  "error" => "Resource not found",
  "message" => "The requested resource was not found."
);

// Return the error response to the client
echo json_encode($errorResponse);

By handling errors and exceptions appropriately, setting the correct HTTP status codes, and providing meaningful error messages in JSON format, you can enhance the usability and debugging experience of your RESTful API.

Clients will have a clearer understanding of encountered errors and can take appropriate action to resolve them.

Testing the API.

There are multiple methods and tools at your disposal for testing RESTful APIs, including popular options like Postman and cURL. These tools provide a convenient way to send HTTP requests directly to your API endpoints and examine the corresponding responses.

Postman is an extensively employed tool for API development and testing. It provides a user-friendly interface that simplifies the process of sending requests and examining the corresponding responses. With Postman, you can easily configure request headers, query parameters, and request bodies, allowing you to test your API in different scenarios. Its intuitive interface makes it a favored option among developers for effective testing and debugging of RESTful APIs.

On the flip side, cURL is a command-line utility that facilitates making HTTP requests. It is extensively supported across various operating systems, allowing you to directly test APIs through the command line interface. The ability to script and automate cURL commands makes it a valuable tool for testing purposes and seamless integration with other tools. Its wide availability and versatility make cURL a practical choice for developers seeking to test APIs and streamline their development workflow.

Here’s an example of sending a POST request to create a new user and receiving a success response using cURL:

curl -X POST -H "Content-Type: application/json" -d '{"username": "john", "password": "secret"}' http://api.example.com/users

Expected response:

HTTP/1.1 201 Created
{
  "message": "User created successfully."
}

API testing and debugging best practices include:

  • Use descriptive and meaningful test data– Use test data covering different scenarios and edge cases to make sure your API can handle different situations correctly.
  • Test edge cases– Test with inputs that lie on the expected data range boundaries to ensure the API handles them correctly.
  • Log the error for troubleshooting– Implement a logging mechanism to capture errors and exceptions during API testing. This helps identify and resolve issues quickly. 

Deploying the API.

There are two main options for exposing PHP and MySQL based APIs.

Use a hosting provider or deploy on a self-managed server.

Consider factors such as scalability, security, cost, and support when choosing a hosting provider. Popular hosting providers for PHP and MySQL include AWS, Google Cloud, and DigitalOcean. These platforms offer different services and plans to deploy and manage APIs. 

If you would rather have control over your server management, you have the option to set up a virtual private server (VPS) or a dedicated server. This choice grants you more autonomy; however, it does necessitate technical proficiency in server administration.

Here is a summary of the steps to deploy your API:

  • Choose a hosting provider or set up your own server.
  • Install and configure a web server such as Apache or Nginx on your server.
  • Upload the PHP file to your server and place it in the correct directory.
  • Export the MySQL database and import it into the MySQL server on your server.
  • Adapt your API configuration settings to your server environment. Thoroughly tested APIs to ensure proper functionality.

Please refer to your hosting provider or server management platform’s documentation or policies for detailed instructions on exposing PHP and MySQL-based APIs.

These resources provide specific information and best practices tailored to your platform of choice to ensure a smooth deployment process.  

Example of a RESTful API with PHP and MySQL.

The code below serves as a comprehensive example of building a RESTful API using PHP and MySQL. It includes all the concepts we’ve discussed so far, such as: B. Handle different kinds of requests, interact with databases, provide appropriate responses, and incorporate security measures.

This code contains a fully functional RESTful API using PHP and MySQL. Handles GET, POST, PUT, and DELETE requests to retrieve, create, update, and delete user information from the database. It also uses prepared statements to prevent SQL injection vulnerabilities and returns JSON-encoded responses for greater compatibility. Note:

Be sure to replace “your_username”, “your_password”, and “your_databasename” with her actual MySQL credentials.  

<?php
// Set up database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle GET request to fetch user information
if ($_SERVER["REQUEST_METHOD"] === "GET") {
    if (isset($_GET["id"])) {
        $id = $_GET["id"];
        $sql = "SELECT * FROM users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            echo json_encode($row);
        } else {
            http_response_code(404);
            echo json_encode(array("message" => "User not found."));
        }
    } else {
        $sql = "SELECT * FROM users";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $rows = array();
            while ($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            echo json_encode($rows);
        } else {
            echo json_encode(array("message" => "No users found."));
        }
    }
}

// Handle POST request to create a new user
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);

    if (isset($data["name"]) && isset($data["email"])) {
        $name = $data["name"];
        $email = $data["email"];

        $sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $name, $email);

        if ($stmt->execute()) {
            $userId = $stmt->insert_id;
            echo json_encode(array("message" => "New user created with ID: " . $userId));
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Error: " . $stmt->error));
        }
    } else {
        http_response_code(400);
        echo json_encode(array("message" => "Invalid input data."));
    }
}

// Handle PUT request to update user information
if ($_SERVER["REQUEST_METHOD"] === "PUT") {
    $data = json_decode(file_get_contents("php://input"), true);

    if (isset($_GET["id"]) && isset($data["name"]) && isset($data["email"])) {
        $id = $_GET["id"];
        $name = $data["name"];
        $email = $data["email"];

        $sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssi", $name, $email, $id);

        if ($stmt->execute()) {
            echo json_encode(array("message" => "User updated successfully."));
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Error: " . $stmt->error));
        }
    } else {
        http_response_code(400);
        echo json_encode(array("message" => "Invalid input data."));
    }
}

// Handle DELETE request to delete a user
if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
    if (isset($_GET["id"])) {
        $id = $_GET["id"];
        $sql = "DELETE FROM users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            echo json_encode(array("message" => "User deleted successfully."));
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Error: " . $stmt->error));
        }
    } else {
        http_response_code(400);
        echo json_encode(array("message" => "Invalid input data."));
    }
}

// Close database connection
$conn->close();
?>

Please note that this sample example can be expanded upon to include additional functionality, validation, authentication, and other enhancements that align with your specific requirements and industry best practices.

Conclusion.

This tutorial provides an overview of building a RESTful API using PHP and MySQL. 

Covers various aspects such as setting up a development environment, designing a database schema, building a PHP backend, handling API requests, interacting with MySQL, implementing authentication and authorization, handling errors and exceptions, testing and serving APIs. doing.

By following this tutorial, you will have the knowledge and skills necessary to effectively use PHP and MySQL when developing functional RESTful APIs. It allows you to create compelling web applications and services that meet the demands of modern web development. 

Some additional resources to facilitate your learning. 

PHP.net (https://www.php.net/docs.php): The official PHP documentation provides comprehensive information on PHP functions, syntax, and best practices.

MySQL Documentation (https://dev.mysql.com/doc/): The official MySQL documentation offers detailed guides, tutorials, and references for working with MySQL databases.

Related Posts

cURL in PHP: A Comprehensive Tutorial
cURL in PHP: A Comprehensive Tutorial

cURL is a powerful tool that can handle all sorts of data-related tasks in PHP…

Read More
How to Use Try Catch in PHP for Effective Debugging.
How to Use Try Catch in PHP for Effective Debugging.

Programming errors are a part of all software development. PHP is no exception! Handling errors…

Read More