PHP - Create a simple REST API

By xngo on October 2, 2019

In this tutorial, I will show you how to create a simple rest api using PHP. You will need MySQL server, PDO driver for MySQL and cURL. At the end of this tutorial, you should have the following files at these locations.

/var/www/html/rest-api/
├── create.php
├── database.php
├── employee.php
└── read.php

Setup database

Create database structure in MySQL

-- Create rest_api_db database name.
CREATE DATABASE rest_api_db;
 
-- Create employee table.
CREATE TABLE employee(
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name TEXT,
    ROLE TEXT);

Connect to database

The Database class below will be used to connect to your database. It contains the database credentials and a method to get a database connection using PDO.

// database.php
class Database{
 
    // Specify your own database credentials.
    private $host = "localhost";
    private $db_name = "rest_api_db";
    private $username = "YOUR_USERNAME";
    private $password = "YOUR_PASSWORD";
    public $conn;
 
    public function getConnection(){
 
        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host
                                    . ";dbname=" . $this->db_name,
                                    $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }
}

Implement Employee class

The Employee class below will do all the heavy lifting with the employee table.

// employee.php
class Employee{
    private $conn;
 
    // Object properties.
    public $id;
    public $name;
    public $role;
 
    // Constructor with $db as database connection.
    public function __construct($db){
        $this->conn = $db;
    }
 
    // Return all employees.
    function readAll(){
 
        // Query to select all records.
        $query = "SELECT * FROM employee";
 
        // Prepare query.
        $stmt = $this->conn->prepare($query);
 
        // Execute query.
        if($stmt->execute()){
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            return $results;
        }
        else{
            print_r($stmt->errorInfo());
            return array();
        }
    }
 
    // Create an employee.
    function create(){
 
        // Query to insert a record.
        $query = "INSERT INTO employee(name, role) VALUES(:name, :role)";
 
        // Prepare query.
        $stmt = $this->conn->prepare($query);
 
        // Sanitize inputs.
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->role=htmlspecialchars(strip_tags($this->role));
 
        // Bind values.
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":role", $this->role);
 
        // Execute query.
        if($stmt->execute()){
            return true;
        }
        else{
            print_r($stmt->errorInfo());
            return false;
        }
    }
}

Create an employees

Create create.php file

The create.php file below will get the JSON data and then process it with the help of the Employee class.

// Required headers.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, 
            Access-Control-Allow-Headers, Authorization, X-Requested-With");
 
include_once __DIR__.'/database.php';
include_once __DIR__.'/employee.php';
 
// Get database connection.
$database = new Database();
$db = $database->getConnection();
 
$employee = new Employee($db);
 
// Get posted JSON data.
$data = json_decode(file_get_contents("php://input"));
 
// Set employee property values
$employee->name = $data->name;
$employee->role = $data->role;
 
// Create the employee
if($employee->create()){
 
    // Set response code - 201 created.
    http_response_code(201);
 
    // Return message to user on success.
    echo json_encode(array("message" => "Employee was created."));
}
else{ // If create employee failed.
 
    // Set response code - 503 service unavailable.
    http_response_code(503);
 
    // Return message to user on failure.
    echo json_encode(array("message" => "Unable to create employee."));
}

Test creating an employee with JSON

You can post JSON data as string or from a file using cURL. Here are the examples.

# Post JSON data as string.
curl -X POST -H "Content-Type: application/json" \
        -d '{ "name":"abc", "role":"role" }' http://localhost/rest-api/create.php
 
# Post JSON data from a file.
curl -X POST -H "Content-Type: application/json" \
        -d @data.json  http://localhost/rest-api/create.php

The data.json file contains the JSON string { "name":"abc", "role":"role" }.

On success, you will get the following return message.

{"message":"Employee was created."}

On failure, you will get the following return message.

{"message":"Unable to create employee."}

Get Employee

Create read.php file

The read.php file below will return all employees in JSON format.

include_once __DIR__.'/database.php';
include_once __DIR__.'/employee.php';
 
// Get database connection.
$database = new Database();
$db = $database->getConnection();
 
$employee = new Employee($db);
 
// Read employee table.
$results = $employee->readAll();
if(sizeof($results)>0){
 
    // Set response code - 200 OK.
    http_response_code(200);
 
    // Return data in json format.
    echo json_encode($results);
}
else{   // If readAll() failed.
 
    // Set response code - 404 Not found.
    http_response_code(404);
 
    // Return message to user on failure.
    echo json_encode(
        array("message" => "No employee found.")
    );
}

Fetch all employees in JSON format

Run the following command to get all employees in JSON format:

curl http://localhost/rest-api/create.php

Output for my case

[ 
    { 
        "id":"1",
        "name":"abc",
        "role":"role"
    },
    { 
        "id":"2",
        "name":"name",
        "role":"role"
    }
]

Github

  • The complete example can be found at https://github.com/xuanngo2001/php-opw-examples/tree/master/rest-api.
  • Copy that folder and follow the readme file.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.