REST API CRUD using PHP Example

51

In this tutorial, we are going to create a RESTful web service in PHP for performing the CRUD operations. In previous tutorials, we have seen examples for MySQL CRUD and for creating a RESTful web service using PHP. In this tutorial which is part of the REST API series, let us learn about how to provide a simple REST API for CRUD (Create, Read, Update and Delete) operations. We will not be using any framework as dependencies, the complete implementation will be using plain core PHP.

Let us see about the conventions I have used in this example. The READ and DELETE actions are executed by sending the action keyword in the URL and is parsed by the GET method. In the REST Search tutorial,  we have used this method to send the search keyword as a query parameter in the URL to be searched. The ADD and UPDATE actions are called by sending the request data using POST method.

REST API Create and Update Implementation

CREATE and UPDATE requests are sent with the posted values. The UPDATE  request URL will contain the id of a particular row to be updated.

After receiving this request, the REST CRUD service will call the domain class to perform the database insert. The domain class will generate insert query using the posted values. The following figure shows how to POST data for the CREATE or UPDATE request.

I am using the “Advanced REST Client” Google Chrome plugin to test the REST APIs.

Delete using REST API

The DELETE request URL will be same as the EDIT URL. The record ID to be deleted should be passed in the URL After delete, the API response will be like as shown below.

Domain Class used for this CRUD Example

The following code shows the Mobile domain class that contains the function for performing the database CRUD operations. These functions are called by the REST handler class based on the request sent from the client. The domain class CRUD functions will return array response to the REST handler which is encoded as JSON format.

 

Leave A Reply

Your email address will not be published.