kingsoft / persist-rest
REST interface for \Kingsoft\Persist classes
Requires
- kingsoft/db: ^2.7
- kingsoft/http: ^3.11.0
- kingsoft/persist: ^3.0
- psr/log: ^3.0
Requires (Dev)
- phpunit/phpunit: ^11.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- 2.22.0
- 2.21.1
- 2.21.0
- 2.20.0
- 2.19.0
- 2.18.0
- 2.17.0
- 2.16.0
- 2.15.0
- 2.14.0
- 2.13.0
- 2.12.0
- 2.11.2
- 2.11.1
- 2.11.0
- 2.10.3
- 2.10.2
- 2.10.1
- 2.10.0
- 2.9.4
- 2.9.3
- 2.9.2
- 2.9.1
- 2.9.0
- 2.8.7
- 2.8.6
- 2.8.5
- 2.8.1
- 2.8.0
- 2.7.8
- 2.7.7
- 2.7.6
- 1.2.1
- 1.2.0
- 1.1.0
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- 0.1.5
- 0.1.4
- 0.1.3
- 0.1.2
- 0.1.1
- 0.1.0
- dev-copilot/generate-exception-for-missing-pk
- dev-kingma-sbw/issue46
This package is auto-updated.
Last update: 2026-12-02 00:32:43 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/resourcewill 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/resourcegets a list of all resources restricted bymaxresults(R) - GET
https://example.com/resource[n,c]gets a list of resource starting with positionnand limited byc. The response will include links for pagination. (R) - GET
https://example.com/resource/<id>get the record withidspecified (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 theidspecified (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/HEADwithIf-None-Match: <etag>returns304 Not Modifiedwhen the record (or the list) has not changed.PUT,PATCHandDELETEwithIf-Match: <etag>return412 Precondition Failedwhen 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.
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
405with anAllowheader.OPTIONSis always handled byPersistRest. $this->apiis thePersistRestinstance:$this->api->requestholds the parsed request,$this->api->loggerthe logger, and$this->api->get()(orpost(),put(), ...) runs the default behaviour for an endpoint that has a table class.- A handler method sends the response itself. An
InvalidArgumentExceptiongives400, any other exception500.
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; }