MagratheaPHP2
Up to date Narrative last written —; no source changes since. Method signatures below are reflected live.

MagratheaApi — RESTful API Framework

File: src/MagratheaApi.php Namespace: Magrathea2

The central class for building RESTful APIs. Handles routing, CORS, request parsing, response formatting, JWT authorization, and caching. The recommended entry point for any API-first application.


Quick Start

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Magrathea2\MagratheaPHP;
use Magrathea2\MagratheaApi;

MagratheaPHP::Instance()->AppPath(__DIR__)->Prod()->Load()->Connect();

$api = new MagratheaApi();
$api->AllowAll();

$api->Add("GET", "/ping", null, function() {
    return ["status" => "ok"];
});

$api->Run();

Properties

PropertyTypeDescription
$controlstringDefault control class
$actionstringDefault action
$paramsarrayRequest parameters
$returnRawboolWhether to skip JSON encoding
$apiAddress?stringBase API path prefix
$authClass?MagratheaApiAuthAuthorization class
$baseAuth?stringDefault auth method name
$endpointsarrayAll registered routes
$fallbackcallable|nullFallback for unmatched routes

Configuration Methods

SetAddress(string $addr): MagratheaApi

Set a base path prefix for all routes (e.g., /api/v1).

$api->SetAddress("/api/v1");
// Routes like "/users" become "/api/v1/users"

GetAddress(): string|null

Returns the current base address.

AllowAll(): MagratheaApi

Set Access-Control-Allow-Origin: * (CORS open to all origins).

$api->AllowAll();

Allow(array $allowedOrigins): MagratheaApi

Restrict CORS to specific origins.

$api->Allow(["https://myapp.com", "https://admin.myapp.com"]);

DisableCache(): MagratheaApi

Send Cache-Control: no-cache headers.

AddAcceptHeaders(string|array $accept): void

Append allowed request headers.

$api->AddAcceptHeaders(["X-Api-Key", "X-Custom-Header"]);

AcceptHeaders(?array $headers): void

Set the full list of accepted request headers.

SetRaw(): MagratheaApi

Disable JSON encoding of responses — return raw output.

Raw mode (SetRaw(), Run(true)) also bypasses the response cache: ExecuteUrl() calls MagratheaCache::Instance()->Bypass(), so a cached action always runs and returns fresh data, and nothing is saved. Before 2.4.0, a cache hit or save in raw mode printed the JSON and ended the script.

BaseAuthorization(MagratheaApiAuth $authClass, ?string $function): MagratheaApi

Set a default authorization check applied to all protected routes. $authClass must extend MagratheaApiAuth (see the Authentication page); a plain MagratheaApiControl throws a TypeError. Before 2.4.0 the parameter was typed MagratheaApiControl, but a plain control failed anyway when it was stored.

$api->BaseAuthorization(new AuthControl(), "ValidateToken");

When a protected route's auth method returns false, the request stops there: the response is a 401 error (code 401, "Authorization Failed! (<method> = false)", with the auth class's authenticationErrorData as error) and the action is never called. This holds in raw mode too (Run(true), SetRaw(), ExecuteUrl()), where the error array is returned instead of printed. Before 2.4.0, raw mode ran the action anyway after building the error.


Registering Endpoints

Add(string $method, string $url, ?MagratheaApiControl $control, string|callable $function, string|bool $auth = false, ?string $description = null): MagratheaApi

Register a single route.

ParameterDescription
$methodHTTP verb: "GET", "POST", "PUT", "DELETE", "PATCH"
$urlRoute pattern, supports {param} placeholders
$controlController instance (null for closure-only routes)
$functionMethod name string or a callable (closure)
$authfalse = no auth, true = use base auth, string = named auth method
$descriptionOptional route description (shown in API explorer)
// Closure route
$api->Add("GET", "/hello", null, function() {
    return ["message" => "Hello!"];
});

// Controller method
$api->Add("GET", "/users", new UserApiControl(), "List");
$api->Add("GET", "/users/{id}", new UserApiControl(), "Read");
$api->Add("POST", "/users", new UserApiControl(), "Create", true); // auth required

// Route with description
$api->Add("DELETE", "/users/{id}", new UserApiControl(), "Delete", true,
    "Delete a user by ID (requires admin token)");

Crud(string|array $url, MagratheaApiControl $control, string|bool $auth = false): MagratheaApi

Registers a full CRUD suite for a resource in one call:

MethodRouteController Method
GET/resourceList()
GET/resource/{id}Read($params)
POST/resourceCreate($data)
PUT/resource/{id}Update($params)
DELETE/resource/{id}Delete($params)
$api->Crud("/products", new ProductApiControl());

// With auth on all CRUD methods:
$api->Crud("/products", new ProductApiControl(), true);

Crud() always registers Update under PUT, never PATCH — if you also want a PATCH route for the same resource/handler, register it yourself with Add():

$api->Crud("/products", new ProductApiControl());
$api->Add("PATCH", "/products/{id}", new ProductApiControl(), "Update", true);

Both PUT and PATCH bodies are read the same way in a controller — GetPut() (or its alias GetPatch()) returns the decoded body regardless of which of the two verbs was used.

Fallback(callable $fn): MagratheaApi

Register a fallback handler for routes that don't match anything.

$api->Fallback(function() {
    return ["error" => "Route not found"];
});

HealthCheck(bool $checkDatabase = false): void

Registers a GET /health-check endpoint that always returns health and time.

When $checkDatabase is true, it also checks DB connectivity and adds database with "ok" or "fail".

$api->HealthCheck();
// {"health":"ok","time":"2026-07-20 10:00:00"}

$api->HealthCheck(true);
// {"health":"ok","time":"2026-07-20 10:00:00","database":"ok"}

Running the API

Run(bool $returnRaw = false): mixed

Matches the incoming request to a route, calls the controller/closure, and outputs the JSON response.

$api->Run();

ExecuteUrl(string $fullUrl, string $method = "GET"): mixed

Manually execute a URL against this API (useful for internal subrequests or tests).

$result = $api->ExecuteUrl("/products/1", "GET");

Response Helpers

These are typically called from within controllers, but can also be called directly.

Json(array|object $response, int $code = 200): mixed

Output a JSON response with an HTTP status code. In DEV and DEBUG, an associative-array response also gets _debug (see DEV and DEBUG: debug items go to _debug).

$api->Json(["error" => "Not found"], 404);

ReturnSuccess(mixed $data): mixed

Return a standardized success response:

{"success": true, "data": ...}

If $data is a MagratheaPagination instance, a paginated envelope is returned instead:

{"success": true, "data": [...], "page": 0, "count": 20, "has_more": true, "total": 143}

total is only included when it was computed (see MagratheaModelControl::GetPagination()). Just return a MagratheaPagination from a controller action — no other code changes needed:

public function List(array $params = []): MagratheaPagination {
    $query = Query::Select()->Obj(new Article())->Where(["published" => 1])->Order("created_at DESC");
    return ArticleControl::GetPagination($query, page: (int)($params["page"] ?? 0), limit: 20);
}

ReturnFail(mixed $data): mixed

Return a standardized failure response:

{"success": false, "data": ...}

An exception (any \Throwable) is sent as {"message": ..., "code": ...} (code only when it isn't 0), plus "data" for a MagratheaApiException with data, and the HTTP status comes from the exception (see Error responses and HTTP status): 500 for code 0. Anything else is sent as data as is, with HTTP 200.

ReturnError(int $code = 500, string $message = "", mixed $data = null, ?int $status = null): mixed

Return a standardized error response. With no $status, the HTTP status is derived from $data when it's an exception (as in Error responses and HTTP status), otherwise from $code; an explicit $status is sent as given.

$api->ReturnError(404, "Not here");          // HTTP 404
$api->ReturnError(4031, "Plan expired");     // HTTP 403
$api->ReturnError(1062, "Duplicate entry");  // HTTP 500 (doesn't map to 400-599)
$api->ReturnError(4031, "Soft fail", null, 200); // HTTP 200, explicit

Return404(): mixed

Return a 404 response (HTTP 404).

ReturnInternalError(\Error $error): mixed (protected)

Sends a PHP \Error (TypeError, Error, ...) thrown by an action or an auth method as HTTP 500, and logs it with Logger::LogError() (class, message, file and line); if the Logger can't write, it goes to PHP's error_log(). The client gets the details only in DEV:

// DEV
{"success": false, "data": {"message": "...must be of type int, string given...", "error": "TypeError", "file": "/var/www/app/Api/X.php:40"}}
// any other mode
{"success": false, "data": {"message": "Internal Server Error"}}

Before 2.4.0 these weren't caught: PHP's fatal error page was sent instead of JSON. AdminApi does the same (it runs in LOG mode, so its clients always get the generic message).

ReturnApiException(MagratheaApiException $exception): mixed

Return an error response derived from an exception, with the HTTP status from the exception.

When the debugger is DEV or ANALYSIS, ReturnError() and ReturnApiException() add a stacktrace to data. Each frame has file, line, function, class and type, but no args (since 2.4.0), so config arrays, passwords and keys passed down the call chain never reach the response. In other debug modes there's no stacktrace at all.

Cache(array $data): void

Store and immediately return a cached response.

Error responses and HTTP status

Every error response has a 4xx/5xx HTTP status (since 2.4.0; before, everything except ReturnApiException() and the 401 of a failed authorization was sent as HTTP 200). The body is unchanged: {"success": false, "data": ...}.

The status comes from the error code:

CodeHTTP statusExample
3 digitsthe code404 → 404
4 digitscode / 104031 → 403 (sub-codes 0-9)
5 digits, 10000-59999code / 10040312 → 403 (sub-codes 00-99)
anything else, or a result outside 400-5995000, 1062 (106), 2001 (200), 7000 (700), "23000"

For a MagratheaApiException, a status set with SetStatus() wins if it's 400-599; otherwise the code decides. Whether it's a "killer" error ($kill) doesn't change the status.

A database error (MagratheaDBException, including MagratheaDBConnectionLostException, or a raw mysqli_sql_exception) is always 500 (since 2.4.0): its code is MySQL's errno, not a status, and some errnos would map to a 4xx (MySQL's 4031 → 403, MariaDB's 4025 → 402).

What ExecuteUrl() sends:

CaseResponseHTTP status
no routeReturnError(404, ...)404
auth method returned falseReturnError(401, ...)401
action method doesn't existReturnError(500, ...)500
MagratheaApiExceptionReturnApiException()SetStatus() or from the code
other exception, code 0ReturnFail(): {message}500
other exception, code ≠ 0ReturnError(code, message, exception)from the code (500 for a DB error)
PHP \Error (TypeError, ...) in the action or the auth methodReturnInternalError()500

In raw mode (Run(true), SetRaw()) nothing is sent: the response array is returned, without the status.

Clients that don't reject on 4xx/5xx (fetch()) see no difference. axios, jQuery $.ajax, Angular HttpClient and similar send these responses to their error handler, where the body is in error.response.data (axios) / jqXHR.responseJSON (jQuery).


Endpoint Introspection

GetEndpoints(): array

Returns all registered endpoints grouped by URL and method.

GetEndpointsDetail(): array

Returns detailed endpoint info including descriptions.

$endpoints = $api->GetEndpoints();
// Used by the Admin API Explorer feature

Debug Mode

Debug(): MagratheaApi

Enable endpoint debugging — outputs route resolution info.

$api->Debug()->Run();

DEV and DEBUG: debug items go to _debug

In DEV, the Debugger prints every debug item as <pre> where it's added, including every MagratheaException when it's created, even ones that are caught. In DEBUG (->Debug()) it prints them all at the end of the request. In an API response that HTML would break the JSON, so while ExecuteUrl() runs (and so Run()), DEV and DEBUG collect the items instead, and the response gets them as _debug (since 2.4.0). In DEBUG, _debug starts with the items stored before the call, and nothing is printed after a JSON response:

{
  "success": true,
  "data": {"id": 7},
  "_debug": [
    {"type": "Magrathea2\\Exceptions\\MagratheaException", "message": "caught one", "code": 42, "file": "/var/www/app/Api/X.php:40", "data": {"id": 7}},
    {"type": "Magrathea2\\Exceptions\\MagratheaDBException", "message": "Duplicate entry...", "code": 0, "file": "...", "query": "INSERT ...", "values": ["..."]},
    "a string passed to Debugger::Add()",
    "INFO: from Debugger::Info()"
  ]
}

URL Parameter Parsing

Route parameters defined with {param} are passed to the controller method:

$api->Add("GET", "/users/{id}/orders/{orderId}", new OrderControl(), "GetByUser");

// In OrderControl:
public function GetByUser(array $params): array {
    $userId  = $params["id"];
    $orderId = $params["orderId"];
    // ...
}

Full Example: Products API

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Magrathea2\MagratheaPHP;
use Magrathea2\MagratheaApi;
use App\Api\ProductApiControl;
use App\Api\AuthControl;

MagratheaPHP::Instance()
    ->AppPath(__DIR__)
    ->AddRootCodeFolder("models", "controls", "api")
    ->Prod()
    ->Load()
    ->Connect();

$api = new MagratheaApi();

$api->Allow(["https://myapp.com"])
    ->SetAddress("/api/v1")
    ->BaseAuthorization(new AuthControl(), "ValidateToken")
    ->DisableCache();

// Public endpoints
$api->Add("GET",  "/products",     new ProductApiControl(), "List");
$api->Add("GET",  "/products/{id}", new ProductApiControl(), "Read");

// Protected endpoints
$api->Add("POST",   "/products",      new ProductApiControl(), "Create", true);
$api->Add("PUT",    "/products/{id}", new ProductApiControl(), "Update", true);
$api->Add("DELETE", "/products/{id}", new ProductApiControl(), "Delete", true);

$api->HealthCheck();

$api->Run();

Notes

Class Reference — MagratheaApi

Magrathea2\MagratheaApi /home/platypusweb/platypusweb.com.br/site/magratheaphp2/src/MagratheaApi.php

Creates and manages a RESTful API server. This class is responsible for routing requests, handling authorization, and returning JSON responses.

AcceptHeaders(?array $headers = null)

Sets the `Access-Control-Allow-Headers` CORS header.

ParamTypeDefault
$headers ?array null
Add(string $method, string $url, ?Magrathea2\MagratheaApiControl $control, callable|string $function, string|bool $auth = false, ?string $description = null): Magrathea2\MagratheaApi

Adds a custom endpoint to the API.

ParamTypeDefault
$method string required
$url string required
$control ?Magrathea2\MagratheaApiControl required
$function callable|string required
$auth string|bool false
$description ?string null
AddAcceptHeaders($accept)

Adds a header to the list of accepted headers for CORS.

ParamTypeDefault
$accept mixed required
Allow(array $allowedOrigins): Magrathea2\MagratheaApi

Includes CORS headers to allow requests from a specific list of origins.

ParamTypeDefault
$allowedOrigins array required
AllowAll(): Magrathea2\MagratheaApi

Includes CORS headers to allow requests from any origin.

BaseAuthorization(Magrathea2\MagratheaApiControl $authClass, ?string $function): Magrathea2\MagratheaApi

Defines the base authorization handler.

ParamTypeDefault
$authClass Magrathea2\MagratheaApiControl required
$function ?string required
Cache($data)

Handles caching for the API response.

ParamTypeDefault
$data mixed required
Crud(array|string $url, Magrathea2\MagratheaApiControl $control, string|bool $auth = false): Magrathea2\MagratheaApi

Adds a standard set of CRUD (Create, Read, Update, Delete) endpoints for a model.

ParamTypeDefault
$url array|string required
$control Magrathea2\MagratheaApiControl required
$auth string|bool false
Debug(): Magrathea2\MagratheaApi

Prints a debug view of all registered endpoints.

DisableCache(): Magrathea2\MagratheaApi

Sets headers to disable browser and proxy caching.

ExecuteUrl($fullUrl, $method = "GET")

Finds the matching endpoint for a given URL and method, and executes it.

ParamTypeDefault
$fullUrl mixed required
$method mixed "GET"
Fallback($fn): Magrathea2\MagratheaApi

Sets a fallback function to be called when no route matches the request.

ParamTypeDefault
$fn mixed required
GetAddress(): ?string

Gets the base address of the API.

GetEndpoints(): array

Gets a structured array of all registered endpoints, grouped by control class.

GetEndpointsDetail()

Gets a detailed list of all endpoints, grouped by URL.

HealthCheck(bool $checkDatabase = false)

Creates a simple `/health-check` endpoint.

ParamTypeDefault
$checkDatabase bool false
Json($response, int $code = 200)

Outputs a JSON response and terminates the script.

ParamTypeDefault
$response mixed required
$code int 200
ReturnApiException($exception)

Formats and returns a MagratheaApiException as a JSON response.

ParamTypeDefault
$exception mixed required
ReturnError($code = 500, $message = "", $data = null, $status = 200)

Returns a generic JSON error response.

ParamTypeDefault
$code mixed 500
$message mixed ""
$data mixed null
$status mixed 200
ReturnFail($data)

Returns a failure JSON response.

ParamTypeDefault
$data mixed required
ReturnSuccess($data)

Returns a successful JSON response. If $data is a MagratheaPagination, builds a paginated envelope instead ({success, data, page, count, has_more, total?}).

ParamTypeDefault
$data mixed required
Run($returnRaw = false)

Starts the API, processes the request, and returns the response.

ParamTypeDefault
$returnRaw mixed false
SetAddress($addr): Magrathea2\MagratheaApi

Sets the base address for the API.

ParamTypeDefault
$addr mixed required
SetRaw(): Magrathea2\MagratheaApi

Configures the API to return the raw result instead of a JSON-encoded response.

Start(): Magrathea2\MagratheaApi

Start the server, getting base calls

__construct()

Constructor. Initializes the endpoint arrays for different HTTP methods.

Examples