How to create Web API service in PHP?


SOAP and REST APIs are the widely used APIs.

Consider the presence of a PHP class named manage.php that helps in managing the entries in a database.

class manage { private $entryId; function __construct($entryId) {
   $this->entryId = $entryId;
} function deleteEntry() {
   //delete $this->entryId from database
}}

On the server, this functionality can be accessed as shown below −

require_once('manage.php');
$m = new manage(12);
$m->deleteEntry();

How can this be accessed by a different server? A third file can be created that will behave like a buffer/an interface that helps access this data. Below is a sample buffer −

Let us call it ‘api/delete.php’

require_once('manage.php');
if(hasPermission($_POST['api_key']) {
   $m = new manage($_POST['entry_id']);
   $m->deleteEntry();
}

Users can send a POST request to the server at http://example.com/api/delete.php with an api_key and an entry_id.

Updated on: 07-Apr-2020

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements