How to create Web API service in PHP?

Web APIs in PHP allow different applications to communicate and exchange data over HTTP. SOAP and REST are the most widely used API architectures for building web services.

Creating a Simple REST API

Let's start with a basic PHP class that manages database entries ?

<?php
class manage {
    private $entryId;
    
    function __construct($entryId) {
        $this->entryId = $entryId;
    }
    
    function deleteEntry() {
        // Delete $this->entryId from database
        // Database connection and deletion logic here
        return "Entry " . $this->entryId . " deleted successfully";
    }
    
    function getEntry() {
        // Retrieve entry from database
        return array(
            'id' => $this->entryId,
            'name' => 'Sample Entry',
            'status' => 'active'
        );
    }
}
?>

Creating the API Endpoint

To make this functionality accessible to external applications, create an API endpoint that acts as an interface ?

<?php
// api/delete.php
header('Content-Type: application/json');
require_once('manage.php');

function hasPermission($api_key) {
    // Validate API key against database or predefined keys
    return $api_key === 'valid_api_key_123';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (hasPermission($input['api_key'])) {
        $m = new manage($input['entry_id']);
        $result = $m->deleteEntry();
        
        echo json_encode(array(
            'status' => 'success',
            'message' => $result
        ));
    } else {
        http_response_code(401);
        echo json_encode(array(
            'status' => 'error',
            'message' => 'Invalid API key'
        ));
    }
} else {
    http_response_code(405);
    echo json_encode(array(
        'status' => 'error',
        'message' => 'Method not allowed'
    ));
}
?>

Complete REST API Example

Here's a more comprehensive API that handles multiple HTTP methods ?

<?php
// api/entries.php
header('Content-Type: application/json');
require_once('manage.php');

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch($method) {
    case 'GET':
        // Retrieve entry
        $entryId = $_GET['id'] ?? null;
        if ($entryId) {
            $m = new manage($entryId);
            $entry = $m->getEntry();
            echo json_encode($entry);
        }
        break;
        
    case 'POST':
        // Create new entry
        echo json_encode(array('message' => 'Entry created'));
        break;
        
    case 'DELETE':
        // Delete entry
        if (hasPermission($input['api_key'])) {
            $m = new manage($input['entry_id']);
            $result = $m->deleteEntry();
            echo json_encode(array('status' => 'success'));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array('error' => 'Method not supported'));
}

function hasPermission($api_key) {
    return $api_key === 'valid_api_key_123';
}
?>

Client Usage

External applications can now access your API using HTTP requests ?

<?php
// Client example using cURL
$url = 'http://example.com/api/delete.php';
$data = json_encode(array(
    'api_key' => 'valid_api_key_123',
    'entry_id' => 12
));

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

Key Features

Feature Description
Authentication API key validation for security
JSON Response Structured data format
HTTP Methods GET, POST, DELETE support
Error Handling Proper HTTP status codes

Conclusion

Creating web APIs in PHP involves building endpoint files that act as interfaces between your application logic and external clients. Use proper authentication, HTTP methods, and JSON responses for professional API development.

Updated on: 2026-03-15T08:40:01+05:30

962 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements