Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

php-crud-api

> 数据库
Open source

Single file PHP script that adds a REST API to a SQL database

3.7K stars0 likes4 views
WebsiteGitHub

About

Single file PHP script that adds a REST API to a SQL database

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:

  • Automatic REST API for Laravel
  • Automatic REST API for Symfony 4
  • Automatic REST API for SlimPHP 4

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:

  • PHP-CRUD-API Quick Start: A customizable, ready to go, docker compose file featuring PHP-CRUD-API.
  • PHP-CRUD-API filter generator: A JavaScript library creating PHP-CRUD-API filters from expressions.
  • JS-CRUD-API: A JavaScript client library for the API of PHP-CRUD-API
  • PHP-API-AUTH: Single file PHP script that is an authentication provider for PHP-CRUD-API
  • PHP-CRUD-UI: Single file PHP script that adds a UI to a PHP-CRUD-API project.
  • PHP-CRUD-ADMIN: Single file PHP script that adds a database admin interface to a PHP-CRUD-API project.
  • PHP-SP-API: Single file PHP script that adds a REST API to a SQL database.
  • dexie-mysql-sync: Synchronization between local IndexedDB and MySQL Database.
  • ra-data-treeql: NPM package that provides a Data Provider for React Admin.
  • scriptPilot/vueuse: Vue Composables in addition to VueUse.org (that support PHP-CRUD-API).
  • scriptPilot/add-php-backend: Add MySQL, phpMyAdmin and PHP-CRUD-API to your dev environment.
  • VUE-CRUD-UI: Single file Vue.js script that adds a UI to a PHP-CRUD-API project.
  • awesome-node-auth: Database-agnostic JWT authentication library for Node.js that can use PHP-CRUD-API as its storage layer (see the

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.

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:

GET /records/posts

It will return:

{
    "records":[
        {
            "id": 1,

Issues· 85 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPapi-serverautomatic-apicruddatabase

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库