Search  
Always will be ready notify the world about expectations as easy as possible: job change page
Aug 15

How to build a simple REST API in PHP?

How to build a simple REST API in PHP?
Author:
Source:
Views:
4988

In this comprehensive tutorial, you’ll discover the step-by-step process to build a simple REST API using PHP and MySQL.

In the modern-day web landscape, REST APIs are extensively utilized for accessing and manipulating data. By incorporating REST APIs into the web application, it will be easy for you to integrate with modern front-end frameworks. In this detailed guide, we’ll guide you through creating a demo application that fetches a list of users from a MySQL database through a REST endpoint.

Get ready to dive into the world of building powerful and scalable APIs!

Essential files for the tutorial

To begin, it’s essential to set up a directory in your localhost that will house the necessary files. For the purposes of this tutorial, let’s assume the directory is named “REST-API”.

1. config.php: file contains the database configuration and establishes a connection to the database using the provided credentials.

2. employee.php: file defines the `Employee` class with methods to interact with the “employee” table. It includes functions to retrieve all employees, get an employee by ID, add a new employee, update an existing employee, and delete an employee.

3. api.php: file serves as the API endpoint and handles incoming requests based on the HTTP method and endpoint. It uses the `Employee` class to perform the requested operations on the “employee” table. The response is returned in JSON format.

4. curl_helper.php: file provides a common cURL request function `sendRequest()` that can be used to send API requests to the specified URL with the specified HTTP method and data.

5. index.php: file contains the API call example along with the request parameters and endpoints.

Build a simple REST API - api files

Database schema

First of all, we need to create a database for our REST API demo, so either you can execute the SQL Query directly in your PHPMyAdmin or you can create the database manually.

Here is the command to create a database.

CREATE DATABASE database_name;

You need to replace the ‘database_name’ with your real name of the database, for this tutorial let’s assume the database name is ’employee_management’

Now, we need to create the “employee” table in the “employee_management” database with the following columns:

CREATE TABLE employee (
  id INT PRIMARY KEY AUTO_INCREMENT,
  emp_name VARCHAR(100) NOT NULL,
  emp_code VARCHAR(20) NOT NULL,
  emp_email VARCHAR(100) NOT NULL,
  emp_phone VARCHAR(20) NOT NULL,
  emp_address VARCHAR(255) NOT NULL,
  emp_designation VARCHAR(100) NOT NULL,
  emp_joining_date DATE NOT NULL
);

This schema defines the “employee” table with columns for storing employee information, you can update the schema as per your requirements.

Files and code explanation

In this discussion, we will detail the configuration of all essential files and codes for developing a Simple Rest API from scratch.

config.php

The “config.php” file plays a vital role in your project as it holds crucial configuration details, particularly the database credentials. This file acts as the gateway to establishing a secure and seamless connection with your database. By properly configuring the “config.php” file, you ensure smooth data operations and maintain the integrity of your application. Let’s delve into the significance of this file and its role in setting up a robust foundation for your project.

<?php
// Database configuration
$hostname = 'localhost';
$username = root;
$password = 'your_password';
$database = 'employee_management';
// Establish database connection
$conn = mysqli_connect($hostname, $username, $password, $database);
// Check connection
if (!$conn) {
    die('Connection failed: ' . mysqli_connect_error());
}
?>

Make sure to update configuration values with the actual information that you are going to use for the demo.

employee.php

The employee.php file takes center stage. Within this file, the powerful Employee class is defined, encompassing essential methods for seamless interaction with the “employee” table. From retrieval to manipulation, this class empowers you to effortlessly handle employee-related data. Prepare to unlock a world of streamlined employee management with the employee.php file at your disposal.

<?php
class Employee
{
    private $conn;
    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    public function getAllEmployees()
    {
        $query = "SELECT * FROM employee";
        $result = mysqli_query($this->conn, $query);
        $employees = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $employees[] = $row;
        }
        return $employees;
    }

    public function getEmployeeById($id)
    {
        $query = "SELECT * FROM employee WHERE id = $id";
        $result = mysqli_query($this->conn, $query);
        $employee = mysqli_fetch_assoc($result);
        return $employee;
    }

    public function addEmployee($data)
    {
        $emp_name = $data['emp_name'];
        $emp_code = $data['emp_code'];
        $emp_email = $data['emp_email'];
        $emp_phone = $data['emp_phone'];
        $emp_address = $data['emp_address'];
        $emp_designation = $data['emp_designation'];
        $emp_joining_date = $data['emp_joining_date'];
        $query = "INSERT INTO employee (emp_name, emp_code, emp_email, emp_phone, emp_address, emp_designation, emp_joining_date)
                  VALUES ('$emp_name', '$emp_code', '$emp_email', '$emp_phone', '$emp_address', '$emp_designation', '$emp_joining_date')";
        $result = mysqli_query($this->conn, $query);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function updateEmployee($id, $data)
    {
        $emp_name = $data['emp_name'];
        $emp_code = $data['emp_code'];
        $emp_email = $data['emp_email'];
        $emp_phone = $data['emp_phone'];
        $emp_address = $data['emp_address'];
        $emp_designation = $data['emp_designation'];
        $emp_joining_date = $data['emp_joining_date'];
        $query = "UPDATE employee SET emp_name = '$emp_name', emp_code = '$emp_code', emp_email = '$emp_email', emp_phone = '$emp_phone', emp_address = '$emp_address', emp_designation = '$emp_designation', emp_joining_date = '$emp_joining_date' WHERE id = $id";
        $result = mysqli_query($this->conn, $query);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function deleteEmployee($id)
    {
        $query = "DELETE FROM employee WHERE id = $id";
        $result = mysqli_query($this->conn, $query);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}
?>

Let’s go through the functions in the provided employee.php Class

1. __construct($conn): This is the constructor method of the `Employee` class. It takes a parameter `$conn`, which represents the database connection. It assigns the value of `$conn` to the private property `$conn` within the class.

2. getAllEmployees(): This method retrieves all the employees from the database. It constructs a SQL query to select all records from the “employee” table. The query is executed using the database connection `$conn`, and the result is fetched as an associative array. The method then iterates through the result set and appends each row to the `$employees` array. Finally, it returns the array containing all the employees.

3. getEmployeeById($id): This method fetches a specific employee from the database based on the provided `$id`. It constructs a SQL query to select the record from the “employee” table where the ID matches the given `$id`. The query is executed, and the result is fetched as an associative array representing a single employee. The method then returns this employee record.

4. addEmployee($data): This method adds a new employee to the database. It expects an associative array `$data` containing the details of the employee. The method extracts each value from the `$data` array, corresponding to the employee’s attributes such as name, code, email, phone, address, designation, and joining date. It constructs an SQL query to insert the employee data into the “employee” table. The query is executed using the database connection `$conn`, and if the insertion is successful, the method returns `true`. Otherwise, it returns `false`.

5. updateEmployee($id, $data): This method updates an existing employee in the database. It expects the `$id` of the employee to be updated and an associative array `$data` containing the updated details. The method extracts the updated values from the `$data` array, similar to the `addEmployee` method. It constructs an SQL query to update the employee record in the “employee” table based on the provided `$id`. The query is executed using the database connection `$conn`, and if the update is successful, the method returns `true`. Otherwise, it returns `false`.

6. deleteEmployee($id): This method deletes an employee from the database based on the provided `$id`. It constructs an SQL query to delete the employee record from the “employee” table where the ID matches the given `$id`. The query is executed using the database connection `$conn`, and if the deletion is successful, the method returns `true`. Otherwise, it returns `false`.

The `Employee` class encapsulates the functionality related to employee data management, including retrieval, insertion, update, and deletion. The constructor initializes the database connection, which is then used by the other methods to interact with the database.

api.php

The file api.php plays a crucial role as the API endpoint, serving as a gateway to efficiently handle requests using the powerful cURL library. With its robust functionality, api.php acts as a central hub. It facilitates seamless communication and data exchange between your web application and external services. By leveraging the power of cURL, this pivotal file ensures smooth and secure interactions, enhancing the overall performance and reliability of the API-driven system.

<?php
require_once 'config.php';
require_once 'Employee.php';
// Create an instance of the Employee class
$employeeObj = new Employee($conn);
// Get the request method
$method = $_SERVER['REQUEST_METHOD'];
// Get the requested endpoint
$endpoint = $_SERVER['PATH_INFO'];
// Set the response content type
header('Content-Type: application/json');
// Process the request
switch ($method) {
    case 'GET':
        if ($endpoint === '/employees') {
            // Get all employees
            $employees = $employeeObj->getAllEmployees();
            echo json_encode($employees);
        } elseif (preg_match('/^\/employees\/(\d+)$/', $endpoint, $matches)) {
            // Get employee by ID
            $employeeId = $matches[1];
            $employee = $employeeObj->getEmployeeById($employeeId);
            echo json_encode($employee);
        }
        break;
    case 'POST':
        if ($endpoint === '/employees') {
            // Add new employee
            $data = json_decode(file_get_contents('php://input'), true);
            $result = $employeeObj->addEmployee($data);
            echo json_encode(['success' => $result]);
        }
        break;
    case 'PUT':
        if (preg_match('/^\/employees\/(\d+)$/', $endpoint, $matches)) {
            // Update employee by ID
            $employeeId = $matches[1];
            $data = json_decode(file_get_contents('php://input'), true);
            $result = $employeeObj->updateEmployee($employeeId, $data);
            echo json_encode(['success' => $result]);
        }
        break;
    case 'DELETE':
        if (preg_match('/^\/employees\/(\d+)$/', $endpoint, $matches)) {
            // Delete employee by ID
            $employeeId = $matches[1];
            $result = $employeeObj->deleteEmployee($employeeId);
            echo json_encode(['success' => $result]);
        }
        break;
}
?>

Let’s break down the provided api.php file code:

1. require_once ‘config.php’;: This line includes the “config.php” file, which typically contains the necessary configuration settings such as database credentials or other global settings.

2. require_once ‘Employee.php’;: This line includes the “Employee.php” file, which defines the `Employee` class and its related functions.

3. $employeeObj = new Employee($conn);: This line creates an instance of the `Employee` class by passing the `$conn` parameter, which represents the database connection.

4. $method = $_SERVER[‘REQUEST_METHOD’];: This line retrieves the HTTP request method (e.g., GET, POST, PUT, DELETE) from the `$_SERVER` superglobal variable.

5. $endpoint = $_SERVER[‘PATH_INFO’];: This line retrieves the requested endpoint or URL path from the `$_SERVER` superglobal variable.

6. header(‘Content-Type: application/json’);: This line sets the response content type to JSON, indicating that the server will send JSON-formatted data in the response.

7. The code then proceeds to process the request based on the HTTP method using a `switch` statement:

In the "GET" case:

- If the endpoint is ‘/employees’, it calls the `getAllEmployees` method from the `$employeeObj` instance to retrieve all employees. The resulting array of employees is encoded as JSON and sent as the response.

- If the endpoint matches the pattern ‘/employees/{id}’, it extracts the employee ID from the endpoint using regular expression matching (`preg_match`). It then calls the `getEmployeeById` method from `$employeeObj` to retrieve the specific employee by their ID. The resulting employee record is encoded as JSON and sent as the response.

In the "POST" case:

- If the endpoint is ‘/employees’, it reads the request payload using `file_get_contents(‘php://input’)` and decodes it as JSON data. The decoded data is passed to the `addEmployee` method of `$employeeObj` to add a new employee. The success status of the operation is encoded as JSON and sent as the response.

In the "PUT" case:

- If the endpoint matches the pattern ‘/employees/{id}’, it extracts the employee ID from the endpoint. It then reads the request payload, decodes it as JSON, and passes the decoded data and employee ID to the `updateEmployee` method of `$employeeObj` to update the employee’s details. The success status of the operation is encoded as JSON and sent as the response.

In the "DELETE" case:

– If the endpoint matches the pattern ‘/employees/{id}’, it extracts the employee ID from the endpoint. It calls the `deleteEmployee` method of `$employeeObj` to delete the employee by their ID. The success status of the operation is encoded as JSON and sent as the response.

The code uses the `json_encode` function to convert the PHP arrays or objects into JSON format before sending them as responses.

This code handles various HTTP methods (GET, POST, PUT, DELETE) and corresponding endpoints to perform CRUD operations (Create, Read, Update, Delete) on employee data using the `Employee` class methods. The response is sent back as JSON-encoded data.

curl_helper.php

When it comes to handling cURL requests, the curl_helper.php file serves as the ultimate ally. This invaluable resource houses a collection of common cURL request functions. It streamlines the process of making HTTP requests and retrieving data from various APIs and web services.

With the curl_helper.php file at your disposal, you can effortlessly execute and manage cURL requests, saving you time and effort in your web development endeavors. Whether you need to retrieve data, send POST requests, or interact with external services, this file is crucial for you.

<?php
function sendRequest($url, $method = 'GET', $data = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    // Set request method
    switch ($method) {
        case 'GET':
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case 'POST':
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            break;
        case 'PUT':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            break;
        case 'DELETE':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
    }
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return json_encode(['response' => $response, 'http_code' => $httpCode]);
}
?>

Let’s break down the above-provided curl_helper.php file codebase and usage for the same:

1. function sendRequest($url, $method = ‘GET’, $data = []): This line declares a function named `sendRequest` that takes three parameters: `$url`, `$method`, and `$data`. The `$method` parameter is optional and defaults to `’GET’`, while the `$data` parameter is an empty array by default.

2. $ch = curl_init();: This line initializes a cURL session and assigns the cURL handle to the variable `$ch`.

3. curl_setopt($ch, CURLOPT_URL, $url);: This line sets the URL to which the cURL request will be sent.

4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);: This line sets the `CURLOPT_RETURNTRANSFER` option to `true`, which tells cURL to return the response as a string instead of outputting it directly.

5. The 'switch' statement handles different HTTP methods and sets the appropriate cURL options accordingly:

– If the method is GET, 'curl_setopt($ch, CURLOPT_HTTPGET, true);' is executed, indicating that it’s a GET request.

– If the method is POST, 'curl_setopt($ch, CURLOPT_POST, true);' sets the request type to POST, and 'curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));' sets the request body as the JSON-encoded `$data`.

– If the method is PUT, 'curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘PUT’);' sets the request type to PUT, and `curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));` sets the request body as the JSON-encoded `$data`.

– If the method is DELETE, 'curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘DELETE’);' sets the request type to DELETE.

6. $response = curl_exec($ch);: This line executes the cURL request and assigns the response to the variable '$response'.

7. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);: This line retrieves the HTTP response code using 'curl_getinfo()' and assigns it to the variable '$httpCode'.

8. curl_close($ch);: This line closes the cURL session and releases the associated resources.

9. Finally, the function returns an array containing the json response and HTTP status code as key-value pairs: 'return json_encode([‘response’ => $response, ‘http_code’ => $httpCode]);'.

This function 'sendRequest()' provides a convenient way to send HTTP requests using cURL. It abstracts the complexity of setting cURL options and handles various HTTP methods (GET, POST, PUT, DELETE) by utilizing the appropriate cURL options. The function returns an array with the response data and the HTTP status code for further processing or handling of the API response.

index.php

demonstrates the seamless integration of API calls, along with their corresponding parameters and endpoints. Uncover the essential elements that make your API interactions smooth and efficient.

<?php
// Include the common cURL file
require_once 'curl_helper.php';
$restAPIBaseURL = 'http://localhost/REST-API';
try {
    // Get all employees
    $employees = sendRequest($restAPIBaseURL.'/api.php/employees', 'GET');
    $employees = json_decode($employees, true);
    // Process the response
    // Get employee by ID
    $employeeId = 1;
    $employee = sendRequest($restAPIBaseURL."/api.php/employees/$employeeId", 'GET');
    $employee = json_decode($employee, true);
    // Process the response
    // Add new employee
    $data = [
        'emp_name' => 'John Doe',
        'emp_code' => 'E001',
        'emp_email' => 'john.doe@example.com',
        'emp_phone' => '1234567890',
        'emp_address' => '123 Street, City',
        'emp_designation' => 'Manager',
        'emp_joining_date' => '2022-01-01',
    ];
    $result = sendRequest($restAPIBaseURL.'/api.php/employees', 'POST', $data);
    $result = json_decode($result, true);
    // Process the response
    // Update employee by ID
    $employeeId = 1;
    $data = [
        'emp_name' => 'Updated Name',
        'emp_code' => 'E002',
        'emp_email' => 'updated.email@example.com',
        'emp_phone' => '9876543210',
        'emp_address' => '456 Street, City',
        'emp_designation' => 'Supervisor',
        'emp_joining_date' => '2022-02-01',
    ];
    $result = sendRequest($restAPIBaseURL."/api.php/employees/$employeeId", 'PUT', $data);
    $result = json_decode($result, true);
     
    // Process the response
    // Handle any additional logic or data processing
} catch (Exception $e) {
    // Handle any exceptions that occur during the API calls
}
?>

Let’s break down the provided index,php code, simply it is a demo that explains how to call a particular API along with the parameters if required.

1. $restAPIBaseURL = ‘http://localhost/REST-API’;: This line defines the base URL for the REST API that will be accessed.

2. The code makes several API requests using the 'sendRequest()' function:

Get all employees:

$employees = sendRequest($restAPIBaseURL.'/api.php/employees', 'GET');
$employees = json_decode($employees, true);

This code sends a GET request to the specified URL to retrieve all employees. The response is stored in the '$employees' variable after decoding the JSON response.

Get employee by ID:

$employeeId = 1;
$employee = sendRequest($restAPIBaseURL."/api.php/employees/$employeeId", 'GET');
$employee = json_decode($employee, true);

This code sends a GET request to retrieve a specific employee by ID. The employee ID is appended to the URL. The response is stored in the `$employee` variable after decoding the JSON response.

Add new employee:

$data = [
    'emp_name' => 'John Doe',
    'emp_code' => 'E001',
    'emp_email' => 'john.doe@example.com',
    'emp_phone' => '1234567890',
    'emp_address' => '123 Street, City',
    'emp_designation' => 'Manager',
    'emp_joining_date' => '2022-01-01',
];
$result = sendRequest($restAPIBaseURL.'/api.php/employees', 'POST', $data);
$result = json_decode($result, true);

This code sends a POST request to add a new employee. The data for the new employee is provided in the '$data' array. The response is stored in the '$result' variable after decoding the JSON response.

Update employee by ID:

$employeeId = 1;
$data = [
         'emp_name' => 'Updated Name',
         'emp_code' => 'E002',
         'emp_email' => 'updated.email@example.com',
         'emp_phone' => '9876543210',
         'emp_address' => '456 Street, City',
         'emp_designation' => 'Supervisor',
         'emp_joining_date' => '2022-02-01',
];
$result = sendRequest($restAPIBaseURL."/api.php/employees/$employeeId", 'PUT', $data);
$result = json_decode($result, true);

This code sends a PUT request to update an existing employee. The employee ID and updated data are provided in the '$employeeId' and '$data' variables, respectively. The response is stored in the '$result' variable after decoding the JSON response.

Delete employee by ID:

$employeeId = 1;
$result = sendRequest($restAPIBaseURL."/api.php/employees/$employeeId", 'DELETE');
$result = json_decode($result, true);

This code sends a DELETE request to delete an employee by ID. The employee ID is provided in the '$employeeId' variable. The response is stored in the '$result' variable after decoding the JSON response.

3. The code may include additional logic or data processing to handle the API responses or any exceptions that occur during the API calls.

Conclusion

The code presented in this tutorial lays a solid foundation for developing a PHP and MySQL-powered REST API to handle employee data effectively. Its versatility allows for seamless customization and expansion to cater to unique project requirements. By leveraging this code as a starting point, you can confidently embark on your journey of developing a powerful and customized REST API solution.

Similar
Jun 27, 2022
Author: Jeffery Cheng
This example shows you the gRpc global exception handler in the unary server handle in gRpc. In microservice, we have two ways to integrate with other internal services. The first way is the Request-Response pattern, which is the most famous....
Aug 23, 2022
Author: Luis Rodrigues
Suppose we are building a web api that contains a route to send notification messages to other systems. For security matters, before sending any notification message, we need to provide some credentials to these systems to they accept our messages....
Feb 8, 2023
Author: Giuseppe Maccario
Introduction Today I am going to show how to create a simple PHP application following the MVC pattern (Model-View-Controller). I was inspired by a PHP course I taught some years ago, and in which I built a simple e-commerce with...
Mar 25
Author: Henrique Siebert Domareski
Pagination allows you to retrieve a large number of records split into pages, instead of returning all the results at once. This is especially useful in scenarios where you need to retrieve a large number of records. In this article,...
Send message
Type
Email
Your name
*Message