Search by

kingsoft / persist-rest

kingsoft

REST interface for \Kingsoft\Persist classes

Package info

github.com/theking2/kingsoft-persist-rest

pkg:composer/kingsoft/persist-rest

Statistics

Installs: 839

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 1

2.22.0 2026-12-02 00:32 UTC

README

This package uses \Kingsoft\Http, \Kingsoft\PersistDb to expose all the tables and views discovered by PersistDb discover.php and of those the ones added to the allowedEndPoints list. If it is not on that list the api will return a 404. So other data is save. A table or view is accessible with, GET, POST, PUT, DELETE reqeests but those can also be restricted using allowedMethods. The reqeust follow the rfc9205 standard with some extensions. This module is CORS complient and can allow or disallow certain methods and communicate that fact by properly responding to a OPTION request. The resulting service it HATEOAS enabled as it provides uris for pagination and other functions.

Methods

  • POST https://example.com/resource will create a new record with the values specifed in the json payload. If the record has autoincrment true a new ID is created and returned (C)
  • GET https://example.com/resource gets a list of all resources restricted by maxresults (R)
  • GET https://example.com/resource[n,c] gets a list of resource starting with position n and limited by c. The response will include links for pagination. (R)
  • GET https://example.com/resource/<id> get the record with id specified (R)
  • GET https://example.com/resource?<key>=<value> gets all the resources matching the filter, see Filters. Combine multiple filters with & (R)
  • PUT https://example.com/resource/<id> will set new values specifed in the json payload (U)
  • DELETE https://example.com/resource/<id> deletes the resource with the id specified (D)

So the facade creates a complete CRUD interface for all resources (tables, views) exposed. Tables and views can be discoverd using the "discover" feature from \Kingsoft\Persist. This will allow to have full access to tables and read access to views or even stored procedures if they produce a result set.

Filters

The first character of a filter value selects the operator. key must be a field of the resource, otherwise the request gets 400.

Filter Selects records where
?name=bob name matches bob (SQL LIKE, so usually case-insensitive)
?name=bo* name starts with bo; * is a wildcard
?age==30 age equals 30
?age=!30 age is not 30
?age=<30 age is smaller than 30
?age=>30 age is greater than 30
?id=~1,2,3 id is one of 1, 2, 3 (SQL IN)
?flags=^4 flags & 4 is not zero (bitwise and)

Bitwise and is written ^ because & separates filters in a URL; an encoded %26 (?flags=%264) works too. Filters can be combined: ?age=>30&name=bo*.

The operators need kingsoft/http 3.11.0 or newer. With kingsoft/persist-db before 2.15.0, < and > are reversed.

Results

GET results are stored in a resources object in the json response allongside links and other messages to make a semi level 3. The results can be a single or multiple objects up to the maximum set. The response will include the urls to implement a pagination.

HATEOAS

Results contain URIs for pagination and other navigation.

List responses include a links array: single (template for one record), prev-page when records precede the page and next-page when more follow. To leave the links out, pass false as the fourth PersistRest argument; partial, first, last and count stay in the response:

$api = new PersistRest( $request, LOG, 86400, false ); // no HATEOAS links

Pre flight

Pre-flight is handled by observing the OPTION method and returning the proper hints:

  • Access-Control-Allow-Headers: Content-Type
  • Access-Control-Allow-Origen
  • Access-Control-Request-Method
  • Origin

The preflight response is cached for 86400 seconds (Access-Control-Max-Age) by default. Pass another number of seconds as the third PersistRest argument, or null to send no Access-Control-Max-Age header:

$api = new PersistRest( $request, LOG, 600 );  // cache preflight for 10 minutes
$api = new PersistRest( $request, LOG, null ); // no Access-Control-Max-Age header

$api->getMaxAge() returns the configured value.

Conditional requests

Responses carry an ETag. Clients can send it back to avoid downloading unchanged data or overwriting someone else's change:

  • GET / HEAD with If-None-Match: <etag> returns 304 Not Modified when the record (or the list) has not changed.
  • PUT, PATCH and DELETE with If-Match: <etag> return 412 Precondition Failed when the record changed since the client read it. If-Match: * only requires that the record exists.

A missing record still returns 404 Not Found, whatever the conditional headers say.

CORS

Sample usage

use Kingsoft\Http\{StatusCode, Response};
use Kingsoft\PersistRest\{PersistRest, PersistRequest};

try {
  $request = new PersistRequest(
    ['Test', 'TestView'],
    "GET, POST",
    "client.example.com",
  );
  $request->setLogger( LOG );
  $api = new PersistRest( $request, LOG );
  $api->handleRequest();
} catch ( Exception $e ) {
  Response::sendError( $e->getMessage(), StatusCode::InternalServerError->value );
}

Allowed methods

The second PersistRequest argument lists the methods the API allows, as a comma separated string or an array:

new PersistRequest( ['Test'], 'OPTIONS,GET,POST' );
new PersistRequest( ['Test'], ['OPTIONS', 'GET', 'POST'] );

Methods can also be limited per resource by passing a map instead of a list. The global methods are the upper bound, and OPTIONS is added to every resource when it is allowed globally:

new PersistRequest( [
  'Board',                           // all global methods
  'BoardScore' => 'GET,POST',
  'LastScores' => ['GET'],
], ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE'] );

A method that is not allowed gets 405 Method Not Allowed with an Allow header listing the methods that are.

Custom endpoint handlers

An endpoint can be handled by its own class instead of the default table access. Extend EndpointHandler, implement any of get(), post(), put(), patch(), delete() and head(), and register the class as the fifth PersistRequest argument:

use Kingsoft\Http\{Response, StatusCode};
use Kingsoft\PersistRest\{EndpointHandler, PersistRequest, PersistRest};

class StatsHandler extends EndpointHandler
{
  public function get(): void
  {
    $payload = [ 'players' => 42 ];
    Response::sendStatusCode( StatusCode::OK );
    Response::sendPayload( $payload );
  }
}

class BoardScoreHandler extends EndpointHandler
{
  public function get(): void { $this->api->get(); }  // default behaviour
  public function post(): void { /* validate, then save */ }
}

$request = new PersistRequest(
  [ 'Board' ],
  'OPTIONS,GET,POST',
  '*',
  0,
  [ 'Stats' => StatsHandler::class, 'BoardScore' => BoardScoreHandler::class ]
);
$api = new PersistRest( $request, LOG );
$api->handleRequest();
  • A handler endpoint does not have to be listed in the allowed endpoints and needs no table class.
  • Only the methods the handler implements are allowed (within the configured methods). Others get 405 with an Allow header. OPTIONS is always handled by PersistRest.
  • $this->api is the PersistRest instance: $this->api->request holds the parsed request, $this->api->logger the logger, and $this->api->get() (or post(), put(), ...) runs the default behaviour for an endpoint that has a table class.
  • A handler method sends the response itself. An InvalidArgumentException gives 400, any other exception 500.

Discover

To discover the tables (and views) in you database use this discover.php in order to create the class files for access. Make sure the DB connection is made in config.php and the SETTINGS global array constant is defined. The class \Kingsoft\Db\Database needs the following configuration:

Important: All tables must have a valid primary key defined. Tables without a primary key will cause an InvalidArgumentException to be thrown during request validation. If you need to work with tables that don't have a primary key, you must first add one to the table structure before running discovery.

const SETTINGS = [ 
    'api' => [ 
        'namespace' => 'kingsoft\\api'
    ],
    'db'  => [ 
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'password',
        'database' => 'database'
    ]
];

where namespace can be adjusted. Discovery can than commence with:

<?php declare(strict_types=1);

require_once 'config/config.php';
const ROOT = __DIR__ . '/';
require 'vendor/autoload.php';

use \Kingsoft\Persist\Db\Bootstrap;
$bootstrap = new Bootstrap( SETTINGS['api']['namespace'] );
$bootstrap->discover();

This will generate the fils in the discovery folder that can be copied to whereever you like as long as you update the composer.json file accordingly and issue a composer dump-autoload to re-read the class location. Example:

{
  "require": {
    "php": "^8.1.0",
    "psr/log":"^3.0.0",
    "monolog/monolog":"3.5.0",
    "kingsoft/monolog-handler":"^1.0.0",
    "kingsoft/utils":"^2.7.0",
    "kingsoft/persist-db": "^2.8.8",
    "kingsoft/persist-rest": "^2.8.7"
  },
  "autoload": {
    "psr-4": {
      "Organisation\Application\\": "./classes/Organisation/Application/"
    }
  }
}

after copying the result of discovery.php to the folder classes/Organisation/Application/

It is ofcourse possible to read the constructor parameters from a configuration file.

Add allowedendpoints

Kingsoft persist-db

To create the allowed endpoints with Kingsoft\Persist-db generate them with http://example.com/vendor/kingsoft/persist-db/src/discover/ Followed by these steps

  • Copy the allowedendpoints settings to the ini file and
  • Copy the psr-4 section to composer.json. After that make sure to reload the autoloader with
composer dump-autoload

And to use pretty URLs a htacess

<FilesMatch "\.(?:ini|htaccess)$">
Require all granted
</FilesMatch>

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /api/index.php

nginx

# nginx configuration by winginx.com

location ~ ^(.*)$ { }

location / {
  rewrite ^(.*)$ /api/index.php;
}