Developer Snippet Diary

PHP REST Api structure

ApiHandler.php

<?php
class APIHandler {
    public function processRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

        // Get action (e.g., users, funds, history)
        $resource = $uri[1] ?? '';
        $action = $uri[2] ?? '';
        
        // Map routes to methods
        if ($resource === 'api') {
            switch ($method) {
                case 'GET':
                    if ($action === 'users') return $this->getUsers();
                    if ($action === 'funds') return $this->getFunds();
                    if ($action === 'history') return $this->getHistory();
                    break;

                case 'POST':
                    if ($action === 'users') return $this->createUser();
                    break;

                default:
                    return $this->response(405, ['error' => 'Method Not Allowed']);
            }
        }

        return $this->response(404, ['error' => 'Not Found']);
    }

    private function getUsers() {
        return $this->response(200, [
            ['id' => 1, 'name' => 'Alice'],
            ['id' => 2, 'name' => 'Bob']
        ]);
    }

    private function getFunds() {
        return $this->response(200, [
            'total' => 5000,
            'available' => 4200
        ]);
    }

    private function getHistory() {
        return $this->response(200, [
            ['action' => 'deposit', 'amount' => 1000],
            ['action' => 'withdrawal', 'amount' => 200]
        ]);
    }

    private function createUser() {
        $input = json_decode(file_get_contents("php://input"), true);
        if (!isset($input['name'])) {
            return $this->response(400, ['error' => 'Name is required']);
        }

        return $this->response(201, [
            'id' => rand(1000, 9999),
            'name' => $input['name']
        ]);
    }

    private function response($status, $data) {
        http_response_code($status);
        header('Content-Type: application/json');
        echo json_encode($data);
    }
}

index.php

<?php
require_once 'APIHandler.php';

$api = new APIHandler();
$api->processRequest();

.htaccess

RewriteEngine On
RewriteBase /api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Now visit:

http://localhost/project/api/funds

 

Posted by: R GONDAL
Email: rizikmw@gmail.com