PHP-CRUD-API
Single file PHP script that adds a REST API to a MySQL/MariaDB, PostgreSQL, SQL
Server or SQLite database.
Howto: Upload "api.php" to your webserver, configure it to connect to your
database, have an instant full-featured REST API.
NB: This is the TreeQL reference implementation in PHP.
Requirements
- PHP 7.2 or higher with PDO drivers enabled for one of these database systems:
- MySQL 5.7 / MariaDB 10.0 or higher for spatial features in MySQL
- PostgreSQL 9.5 or higher with PostGIS 2.2 or higher for spatial features
- SQL Server 2017 or higher (2019 also has Linux support)
- SQLite 3.22 or higher (spatial features NOT supported)
Installation
Download the "api.php" file from the latest release:
https://github.com/mevdschee/php-crud-api/releases/latest or direct from:
https://raw.githubusercontent.com/mevdschee/php-crud-api/main/api.php
This is a single file application! Upload "api.php" somewhere and enjoy!
For local development you may run PHP's built-in web server:
php -S localhost:8080
Test the script by opening the following URL:
http://localhost:8080/api.php/records/posts/1
Don't forget to modify the configuration at the bottom of the file.
Alternatively you can integrate this project into the web framework of your
choice, see:
In these integrations Composer is used to load this
project as a dependency.
For people that don't use composer, the file "api.include.php" is provided.
This file contains everything from "api.php" except the configuration from
"src/index.php" and can be used by PHP's "include" function.
Configuration
Edit the following lines in the bottom of the file "api.php":
$config = new Config([
'username' => 'xxx',
'password' => 'xxx',
'database' => 'xxx',
]);
These are all the configuration options and their default value between
brackets:
- "driver":
mysql, pgsql, sqlsrv or sqlite (mysql)
- "address": Hostname (or filename) of the database server (
localhost)
- "port": TCP port of the database server (defaults to driver default)
- "username": Username of the user connecting to the database (no default)
- "password": Password of the user connecting to the database (no default)
- "database": Database the connecting is made to (no default)
- "command": Extra SQL to initialize the database connection (none)
- "tables": Comma separated list of tables to publish (defaults to 'all')
- "mapping": Comma separated list of table/column mappings (no mappping)
- "geometrySrid": SRID assumed when converting from WKT to geometry (
4326)
- "middlewares": List of middlewares to load (
cors)
- "controllers": List of controllers to load (
records,geojson,openapi,status)
- "customControllers": List of user custom controllers to load (no default)
- "customOpenApiBuilders": List of user custom OpenAPI builders to load (no
default)
- "openApiBase": OpenAPI info
(
{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}})
- "openApiFilterCount": Number of "filter1" to "filterN" parameters described in
the OpenAPI specification (
3)
- "openApiSubFilterCount": Number of lettered filter parameters, such as
"filter1a", described per numbered filter (
0)
- "cacheType":
TempFile, Redis, Memcache, Memcached or NoCache
(TempFile)
- "cachePath": Path/address of the cache (defaults to system's temp directory)
- "cacheTime": Number of seconds the cache is valid (
10)
- "jsonOptions": Options used for encoding JSON (
JSON_UNESCAPED_UNICODE)
- "debug": Show errors in the "X-Exception" headers (
false)
- "basePath": URI base path of the API (determined using PATH_INFO by default)
All configuration options are also available as environment variables. Write the
config option with capitals, a "PHP_CRUD_API_" prefix and underscores for word
breakes, so for instance:
- PHP_CRUD_API_DRIVER=mysql
- PHP_CRUD_API_ADDRESS=localhost
- PHP_CRUD_API_PORT=3306
- PHP_CRUD_API_DATABASE=php-crud-api
- PHP_CRUD_API_USERNAME=php-crud-api
- PHP_CRUD_API_PASSWORD=php-crud-api
- PHP_CRUD_API_DEBUG=1
The environment variables take precedence over the PHP configuration.
Limitations
These limitation and constrains apply:
- Primary keys should either be auto-increment (from 1 to 2^53) or UUID
- Composite primary and composite foreign keys are not supported
- Complex writes (transactions) are not supported
- Complex queries calling functions (like "concat" or "sum") are not supported
- Database must support and define foreign key constraints
- SQLite cannot have bigint typed auto incrementing primary keys
- SQLite does not support altering table columns (structure)
Features
The following features are supported:
- Composer install or single PHP file, easy to deploy.
- Very little code, easy to adapt and maintain
- Supports POST variables as input (x-www-form-urlencoded)
- Supports a JSON object as input
- Supports a JSON array as input (batch insert)
- Sanitize and validate input using type rules and callbacks
- Permission system for databases, tables, columns and records
- Multi-tenant single and multi database layouts are supported
- Multi-domain CORS support for cross-domain requests
- Support for reading joined results from multiple tables
- Search support on multiple criteria
- Pagination, sorting, top N list and column selection
- Relation detection with nested results (belongsTo, hasMany and HABTM)
- Atomic increment support via PATCH (for counters)
- Binary fields supported with base64 encoding
- Spatial/GIS fields and filters supported with WKT and GeoJSON
- Mapping table and column names to support legacy systems
- Generate API documentation using OpenAPI tools
- Authentication via API key, JWT token or username/password
- Database connection parameters may depend on authentication
- Support for reading database structure in JSON
- Support for modifying database structure using REST endpoint
- Security enhancing middleware is included
- Standard compliant: PSR-4, PSR-7, PSR-12, PSR-15 and PSR-17
Related projects and ports
Related projects:
There are also proof-of-concept ports of this script that only support basic
REST CRUD functionality in:
PHP,
Java,
Go,
C# .net core,
Node.js and
Python.
Compilation
You can install all dependencies of this project using the following command:
php install.php
You can compile all files into a single "api.php" file using:
php build.php
Note that you don't use compilation when you integrate this project into another
project or framework (use Composer instead).
Development
You can access the non-compiled code at the URL:
http://localhost:8080/src/records/posts/1
The non-compiled code resides in the "src" and "vendor" directories. The
"vendor" directory contains the dependencies.
Updating dependencies
You can update all dependencies of this project using the following command:
php update.php
This script will install and run Composer to update
the dependencies.
NB: The update script will patch the dependencies in the vendor directory for
PHP 7.0 compatibility.
Version
The version of the release is in the header at the top of "api.php" (and
"api.include.php"), for instance "PHP-CRUD-API v2.16.7". When you build the
file yourself it gets the version of the latest release tag in your checkout.
Releasing
The scripts that publish a new version and the docker image are in the "scripts"
directory, see "scripts/README.md" for how to use them.
TreeQL, a pragmatic GraphQL
TreeQL allows you to create a "tree" of JSON objects based
on your SQL database structure (relations) and your query.
It is loosely based on the REST standard and also inspired by json:api.
CRUD + List
The example posts table has only a a few fields:
posts
=======
id
title
content
created
The CRUD + List operations below act on this table.
Create
If you want to create a record the request can be written in URL format as:
POST /records/posts
You have to send a body containing:
{
"title": "Black is the new red",
"content": "This is the second post.",
"created": "2018-03-06T21:34:01Z"
}
And it will return the value of the primary key of the newly created record:
2
Read
To read a record from this table the request can be written in URL format as:
GET /records/posts/1
Where "1" is the value of the primary key of the record that you want to read.
It will return:
{
"id": 1
"title": "Hello world!",
"content": "Welcome to the first post.",
"created": "2018-03-05T20:12:56Z"
}
On read operations you may apply joins.
Update
To update a record in this table the request can be written in URL format as:
PUT /records/posts/1
Where "1" is the value of the primary key of the record that you want to update.
Send as a body:
{
"title": "Adjusted title!"
}
This adjusts the title of the post. And the return value is the number of rows
that are set:
1
Delete
If you want to delete a record from this table the request can be written in URL
format as:
DELETE /records/posts/1
And it will return the number of deleted rows:
1
List
To list records from this table the request can be written in URL format as: