Create And Consume Simple REST API in PHP

Representational State Transfer (REST) is an architectural style for building distributed systems and APIs. It relies on standard HTTP methods and status codes to enable communication between different systems.

In this guide, we will create a simple REST API in PHP that can perform CRUD (Create, Read, Update, Delete) operations on a database. We will also create a separate PHP script to connect and consume this API.

Overview

Here is a quick overview of what we will do:

  • Set up a MySQL database with a users table
  • Create a PHP script (api.php) that handles REST API requests
  • Support CRUD operations:
  • Create new user (POST)
  • Get all users (GET)
  • Get single user by ID (GET)
  • Update user (PUT)
  • Delete user (DELETE)
  • Output JSON data
  • Create another PHP script (client.php) to connect and consume the API
  • Test the API using cURL and client script

Prerequisites

Before we start, make sure you have the following:

  • PHP 7.0 or higher
  • MySQL or MariaDB
  • Web server like Apache or Nginx
  • REST client like cURL or Postman (optional)

Database Setup

Let’s first create a simple users table in MySQL to store user records:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL
);
JavaScript

Next, insert a couple rows for testing:

INSERT INTO users (name, email) 
VALUES ('John Doe', '[email protected]'),
       ('Jane Doe', '[email protected]');
JavaScript

This will create a users table with some initial rows. We will perform CRUD operations on this table using our API.

API Script (api.php)

Now let’s create our main api.php script which will handle all the API requests and responses:

<?php

// Connect to MySQL database
$conn = mysqli_connect('localhost', 'username', 'password', 'mydatabase');

// Handle GET request - get all users
if ($_SERVER['REQUEST_METHOD'] == 'GET' && !isset($_GET['id'])) {

  $sql = "SELECT * FROM users";

  $result = mysqli_query($conn, $sql);

  $users = mysqli_fetch_all($result, MYSQLI_ASSOC);

  echo json_encode($users);
  exit();

}

// Handle GET request - get single user
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['id'])) {

  $id = mysqli_real_escape_string($conn, $_GET['id']);

  $sql = "SELECT * FROM users WHERE id=$id";

  $result = mysqli_query($conn, $sql);

  if (mysqli_num_rows($result) > 0) {
    $user = mysqli_fetch_assoc($result);
    echo json_encode($user);
  } else {
    echo json_encode(['message' => 'User not found']);
  }

  exit();

}

// Handle POST request - create new user
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  $name = mysqli_real_escape_string($conn, $_POST['name']);
  $email = mysqli_real_escape_string($conn, $_POST['email']);

  $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

  if (mysqli_query($conn, $sql)) {
    $user_id = mysqli_insert_id($conn);
    echo json_encode(['id' => $user_id, 'name' => $name, 'email' => $email]);
  } else {
    echo json_encode(['message' => 'User creation failed']);
  }

  exit();

}

// Handle PUT request - update user
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {

  $id = mysqli_real_escape_string($conn, $_GET['id']);

  $name = mysqli_real_escape_string($conn, $_POST['name']);
  $email = mysqli_real_escape_string($conn, $_POST['email']);

  $sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";

  if (mysqli_query($conn, $sql)) {
    echo json_encode(['message' => 'User updated successfully']);
  } else {
    echo json_encode(['message' => 'User update failed']);
  }

  exit();
}

// Handle DELETE request - delete user
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {

  $id = mysqli_real_escape_string($conn, $_GET['id']);

  $sql = "DELETE FROM users WHERE id=$id";

  if (mysqli_query($conn, $sql)) {
    echo json_encode(['message' => 'User deleted successfully']);
  } else {
    echo json_encode(['message' => 'User deletion failed']); 
  }

  exit();

}

// Return 404 if no routes matched
http_response_code(404);
echo json_encode(['message' => 'Not Found']);
JavaScript

Let’s understand what’s happening above:

  • We connect to the MySQL database
  • Check $_SERVER['REQUEST_METHOD'] to determine HTTP method
  • For GET requests, retrieve users from DB and json_encode() the output
  • For POST requests, insert new user into DB and return response
  • For PUT requests, update user and return response
  • For DELETE requests, delete user and return response
  • Return 404 with JSON error if no routes matched

This simple script handles all CRUD operations for our /users API endpoint.

You can save this as api.php and put it in your web server’s document root.

Consuming the API

To test our API, let’s create a simple client script that interacts with it.

Save this as client.php:

<?php

// Get all users
$users_url = 'http://localhost/api.php';
$users = file_get_contents($users_url);
echo $users . "\n\n";

// Get single user
$user_url = 'http://localhost/api.php?id=2'; 
$user = file_get_contents($user_url);
echo $user . "\n\n";

// Create user
$new_user = [
  'name' => 'Sam Smith',
  'email' => '[email protected]'
];

$create_url = 'http://localhost/api.php';
$response = file_get_contents($create_url, false, stream_context_create([
  'http' => [
    'method' => 'POST',
    'header' => 'Content-type: application/json',
    'content' => json_encode($new_user)
  ]
]));

echo $response . "\n\n";

// Update user
$updated_user = [
  'name' => 'Sam Smith Updated', 
  'email' => '[email protected]'  
];

$update_url = 'http://localhost/api.php?id=3'; 

$response = file_get_contents($update_url, false, stream_context_create([
  'http' => [
    'method' => 'PUT',
    'header' => 'Content-type: application/json',
    'content' => json_encode($updated_user) 
    ]
]));

echo $response . "\n\n";

// Delete user
$delete_url = 'http://localhost/api.php?id=3';

$response = file_get_contents($delete_url, false, stream_context_create([
  'http' => [
    'method' => 'DELETE'
  ]
]));

echo $response;
JavaScript

This scripts sends various requests to our API:

  • GET request to get all users
  • GET request to get single user
  • POST request to create new user
  • PUT request to update user
  • DELETE request to delete user

We can test this easily using cURL from the command line:

$ curl http://localhost/client.php
JavaScript

This will invoke the client script which then interacts with our API.

The client script could also be expanded with error handling, output formatting etc. But this shows the basic idea of consuming our REST API from PHP.

Testing with cURL

Instead of using the client script, we can also test the API directly using cURL.

Get all users:

$ curl -i http://localhost/api.php

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 17:28:13 GMT
Server: Apache/2.4.25 (Debian)
Content-Type: application/json    
Content-Length: 119

[{"id":"1","name":"John Doe","email":"[email protected]"},{"id":"2","name":"Jane Doe","email":"[email protected]"}]
JavaScript

Get single user:

$ curl -i http://localhost/api.php?id=2

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 17:30:44 GMT
Server: Apache/2.4.25 (Debian)   
Content-Type: application/json
Content-Length: 45

{"id":"2","name":"Jane Doe","email":"[email protected]"}
JavaScript

Create user:

$ curl -i -X POST -d 'name=Sam Smith&[email protected]' http://localhost/api.php

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 17:32:11 GMT
Server: Apache/2.4.25 (Debian)
Content-Type: application/json
Content-Length: 62

{"id":"3","name":"Sam Smith","email":"[email protected]"}
JavaScript

Update user:

$ curl -i -X PUT -d 'name=Sam Smith Updated&[email protected]' http://localhost/api.php?id=3

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 17:34:23 GMT
Server: Apache/2.4.25 (Debian)    
Content-Type: application/json
Content-Length: 32

{"message":"User updated successfully"}
JavaScript

Delete user:

$ curl -i -X DELETE http://localhost/api.php?id=3 

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 17:36:44 GMT
Server: Apache/2.4.25 (Debian)
Content-Type: application/json
Content-Length: 34

{"message":"User deleted successfully"}
JavaScript

This allows us to manually test our API endpoints.

Conclusion

That’s it! In this guide, we created a simple REST API in PHP that handles CRUD operations using standard HTTP methods. We can consume it easily from any frontend using AJAX requests and JSON.

Here are some ways you can expand on this:

  • Add authentication
  • Support pagination for GET requests
  • Output different data formats like XML
  • Add more API endpoints and business logic
  • Containerize it using Docker
  • Deploy to a cloud server or PaaS

REST APIs are ubiquitous on the web and knowing how to build them in PHP is useful for many projects. This covers the basics but there is a lot more you can explore!

Leave a Comment