Download the PHP package coagus/php-api-builder without Composer
On this page you can find all versions of the php package coagus/php-api-builder. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-api-builder
PHP API Builder v2
Build RESTful APIs in PHP in minutes. Define your entities, get CRUD automatically, and focus on your business logic.
That's it. You now have a fully functional API with GET, POST, PUT, PATCH, DELETE endpoints, pagination, filtering, sorting, validation, soft deletes, and relationships. No controllers, no routes to configure, no boilerplate.
Features
- Automatic CRUD from entity definitions with zero configuration
- Powerful ORM with Active Record pattern, relationships, and 5-level Query Builder
- PHP 8.4 property hooks, asymmetric visibility, typed properties, attributes as metadata
- Multi-database support via PDO (MySQL, PostgreSQL, SQLite)
- JWT Authentication with OAuth 2.1 security practices (short-lived tokens, refresh rotation, scopes)
- Auto-generated OpenAPI/Swagger documentation from your entity attributes
- Validation via attributes (
#[Required],#[Email],#[MaxLength],#[Unique]) -- no config files - Rate limiting middleware with file-based storage -- no external dependencies
- REST conventions -- lowerCamelCase JSON keys, snake_case query params, RFC 7807 errors
- Security built-in with OWASP headers, CORS, input sanitization, SQL injection protection
- Docker-first workflow -- start a project without PHP installed locally
- CLI scaffolding for entities, services, and middleware
- Error traceability with request ID correlation across all layers
- AI development skill included -- install it and your AI assistant knows the library
Quick Start
With PHP installed
-
Create a new project:
- Initialize and start:
Without PHP (Docker only)
-
Create your project directory:
-
Initialize the project:
-
Start the services:
- Verify it works:
Running CLI commands without PHP: Once
docker compose up -dis running, enter the container and use the CLI from there:Alternatively, the
./apiwrapper auto-detects Docker and works without entering the container.
Try the Demo
Explore all library features with a ready-made Blog API demo:
-
Install the demo (after init + docker compose up):
-
Open Swagger UI at
http://localhost:8080/api/v1/docs/swagger - When done exploring, clean up:
The demo creates a complete Blog API with Users, Posts, Comments, and Tags -- showcasing entities, services, relationships, JWT auth, validation, rate limiting, middleware, and OpenAPI documentation.
Create Your First Entity
This generates entities/User.php:
Your endpoints are ready:
Services (No Database)
Not everything needs a database. Services handle external APIs, health checks, custom logic:
Well-known routes (RFC 8615)
Not every URL belongs under /api/v1. RFC 8615 reserves the /.well-known/* namespace for host-level metadata: OpenID Connect discovery, OAuth 2.0 authorization-server metadata, JWKS, security.txt, and similar. Register these paths with the optional third constructor argument:
The dispatcher consults the wellKnown map before the apiPrefix router, so these paths resolve regardless of the prefix value. Each handler is a regular Service (extends Coagus\PhpApiBuilder\Resource\Service) — its get() method writes a response with $this->success(...) exactly like any other service.
Malformed entries fail fast at construction time. If the class does not exist, the method is not callable on an instance of that class, or the tuple is not [Class::class, 'method'], the API constructor throws InvalidArgumentException before any request is served.
A few notes:
- Global middleware registered via
API::middleware([...])(CORS, security headers, rate limit) still runs for well-known routes. Per-route#[Middleware]attributes are not applied — these endpoints are handled outside the router's class-discovery path. - Well-known paths are deliberately not emitted in the auto-generated OpenAPI document, which only describes
$apiPrefix-scoped resources. - The
wellKnownmap is optional. Omitting it preserves the exact behavior of previous releases.
Hybrid Resources (CRUD + Custom Endpoints)
Combine automatic CRUD with custom business logic:
Per-route Middleware
Attach middleware to a specific resource class or HTTP method with the #[Middleware] attribute. Parameters are forwarded to the middleware constructor as named arguments, and the attribute is repeatable:
The dispatch pipeline runs global middleware first (registered via API::middleware([...])), then class-level #[Middleware], then method-level #[Middleware], then the handler. The middleware class must implement MiddlewareInterface; otherwise dispatch fails loudly.
Virtual Property Hooks with #[Ignore]
#[Ignore] marks a public property as invisible to the ORM, validator, and OpenAPI generator. It pairs naturally with a PHP 8.4 set-only hook that writes to a sibling backing column:
An #[Ignore] property is not written to INSERT/UPDATE, not hydrated from SELECT rows, not checked by the validator, not emitted in response bodies, and not surfaced in OpenAPI schemas. Use it whenever the property exists only to transform input — never as a persisted column.
Query Builder
Five levels of complexity -- use what you need:
Validation via Attributes
#[Required] validates presence, #[Email] validates format, #[Unique] checks the database, #[Hidden] excludes the field from responses, #[Ignore] hides a virtual property from ORM/validator/schemas, and property hooks sanitize on assignment.
Auto-Generated API Documentation
Your entity attributes generate OpenAPI 3.1 specs automatically:
No extra annotations needed. #[Required] becomes required, #[MaxLength(50)] becomes maxLength: 50, #[Hidden] fields are excluded from response schemas.
CLI Commands
The ./api wrapper detects whether to use local PHP or Docker automatically. Teams with mixed setups work seamlessly.
Database Support
Configure in .env:
The ORM generates driver-specific SQL through PDO. Switch databases by changing one line.
Connection URIs (Supabase, RDS, Heroku, Render, …)
Managed Postgres and MySQL hosts publish credentials as a single URI. Pass it directly to Connection::configure() under the dsn key and the library expands it into the individual fields:
Supported schemes: postgresql://, postgres://, mysql://, mariadb://. URL-decoded credentials, default ports (5432 / 3306), and query-string options (e.g. ?sslmode=require) are dropped — libpq and the MySQL driver negotiate TLS automatically against any TLS-enforcing server. Caller-provided fields override URI-parsed ones, so ['dsn' => '...', 'database' => 'override'] wins.
Security
Built-in by default, following OWASP recommendations:
- SQL Injection: Parameterized queries everywhere (PDO prepared statements)
- Security Headers:
X-Content-Type-Options,X-Frame-Options, HSTS,Referrer-Policy - JWT Auth: Short-lived access tokens (15min), refresh rotation with theft detection
- Input Sanitization: Automatic null byte removal, configurable per-field
- CORS: Configurable via
.env, validates against dangerous misconfigurations - Sensitive Data:
#[Hidden]attributes,SensitiveDataFilterin logs
Project Structure
Requirements
- PHP 8.4+
- Composer 2.x
- Or just Docker
Installation
Documentation
Full architecture and design documentation is available in resources/docs/diagrams/.
AI Development Skill
The library includes an AI skill that teaches Claude Code and Cowork how to work with php-api-builder. It is installed automatically by ./api init into .claude/skills/php-api-builder/, so your AI assistant can generate entities, services, queries, and configurations following the library's patterns.
License
MIT License. See LICENSE for details.
Author
Christian Agustin - [email protected]
All versions of php-api-builder with dependencies
firebase/php-jwt Version ^7.0
monolog/monolog Version ^3.5
vlucas/phpdotenv Version ^5.6