Download the PHP package baraja-core/structured-api without Composer
On this page you can find all versions of the php package baraja-core/structured-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download baraja-core/structured-api
More information about baraja-core/structured-api
Files in baraja-core/structured-api
Package structured-api
Short Description Complex library for definition of your structured API endpoint as class with schema.
License
Homepage https://github.com/baraja-core/structured-api
Informations about the package structured-api
Structured REST API in PHP
A powerful, type-safe REST API framework for PHP 8.1+ with full Nette Framework integration. Define structured API endpoints as PHP classes with automatic parameter validation, response serialization, and built-in permission management.
:dart: Key Features
- Type-safe endpoints - Define full type-hint input parameters with automatic validation
- Schema-based responses - Return typed DTOs that are automatically serialized to JSON
- Automatic endpoint discovery - Endpoints are auto-registered via Nette DI container
- Built-in permission system - Role-based access control with
#[PublicEndpoint]and#[Role]attributes - HTTP method routing - Method names determine HTTP verb (GET, POST, PUT, DELETE)
- Tracy debugger integration - Visual debug panel for API request/response inspection
- CORS handling - Automatic Cross-Origin Resource Sharing support
- Dependency injection - Full DI support via constructor or
#[Inject]attribute - Flash messages - Built-in flash message system for API responses
:building_construction: Architecture Overview
The package follows a layered architecture with clear separation of concerns:
Core Components
| Component | Description |
|---|---|
| ApiManager | Central orchestrator that handles routing, CORS, middleware execution, and response processing |
| ApiExtension | Nette DI extension for automatic service registration and configuration |
| BaseEndpoint | Abstract base class providing helper methods for sending responses |
| Endpoint | Interface that marks a class as an API endpoint |
| MetaDataManager | Discovers and registers endpoint classes using RobotLoader |
| Convention | Configuration entity for response formatting, date formats, and security settings |
| PermissionExtension | Middleware for authentication and role-based access control |
| MatchExtension | Interface for creating custom middleware (before/after processing hooks) |
| Tracy Panel | Debug panel showing request details, parameters, and response data |
:framed_picture: Tracy Debug Panel
The package includes a comprehensive Tracy debug panel for inspecting API requests during development:
The panel displays:
- HTTP method and request URL
- Raw HTTP input parameters
- Resolved endpoint arguments after type casting
- Response type, HTTP code, and content type
- Complete serialized response data
- Request processing time in milliseconds
:package: Installation
It's best to use Composer for installation, and you can also find the package on Packagist and GitHub.
To install, simply use the command:
Requirements
- PHP 8.1 or higher
- Extensions:
json,mbstring,iconv - Nette Framework 3.x
Nette Framework Integration
The package integrates automatically with Nette Framework. A model configuration can be found in the common.neon file inside the root of the package.
If you use PackageRegistrator, the extension is registered automatically. Otherwise, register the extension manually in your config.neon:
Configuration Options
:rocket: Basic Usage
Creating Your First Endpoint
Create a class that extends BaseEndpoint with the suffix Endpoint:
This endpoint will be available at:
GET /api/v1/article- callsactionDefault()GET /api/v1/article/detail?id=123- callsactionDetail(123)
Response DTO Objects
For type-safe responses, create DTO classes:
The DTO is automatically serialized to JSON with proper type handling:
DateTimeInterfaceobjects are formatted according toConvention::$dateTimeFormat- Nested objects and arrays are recursively serialized
- Objects with
__toString()method can be converted to strings
:globe_with_meridians: HTTP Methods
The library supports all HTTP methods for REST APIs. The HTTP method is determined by the method name prefix:
Method Prefix Aliases
| Prefix | HTTP Method |
|---|---|
action |
GET |
get |
GET |
post |
POST |
create |
POST |
put |
PUT |
update |
PUT |
delete |
DELETE |
:white_check_mark: Parameter Validation
Method parameters are automatically validated and type-cast:
Validation rules:
- Parameters with default values are optional
- Parameters without defaults are required - request fails if missing
- Type mismatches trigger automatic conversion or error response
- The special parameter
array $datareceives all raw input data
Accessing Raw Data
For complex data structures, use the reserved $data parameter:
:left_speech_bubble: Response Methods
BaseEndpoint provides several helper methods for sending responses:
sendJson()
Send raw array data as JSON:
sendOk()
Send success response with optional data and message:
Response format:
sendError()
Send error response:
Response format:
sendItems()
Send paginated list of items:
Return Statement (Recommended)
The preferred approach is returning typed objects directly:
This enables:
- Static analysis and IDE support
- Automatic documentation generation
- Type safety at compile time
:bell: Flash Messages
Add flash messages to any response:
Available flash message types:
FlashMessageSuccess- successFlashMessageInfo- infoFlashMessageWarning- warningFlashMessageError- error
Flash messages are included in the response under flashMessages key:
:lock: Permissions & Security
Default Security Behavior
All endpoints are private by default. Users must be logged in to access any endpoint unless explicitly marked as public.
Public Endpoints
Mark an entire endpoint as publicly accessible:
Role-Based Access Control
Restrict access to specific user roles:
Restrict specific methods:
Permission Check Flow
- Check if endpoint has
#[PublicEndpoint]attribute - If not public, require user to be logged in (returns 401 if not)
- Check
#[Role]attributes on class and method - If roles defined, verify user has at least one matching role (returns 403 if not)
- If user is logged in and no roles required, allow access
Ignoring Default Permissions
For special cases, you can disable the default permission checking:
:gear: Convention Configuration
The Convention entity controls response formatting and behavior:
:electric_plug: Middleware Extensions
Create custom middleware by implementing MatchExtension:
Register the extension:
:telephone_receiver: Programmatic API Calls
Call endpoints programmatically from PHP code:
:link: URL Routing
API URLs follow this pattern:
Examples
| URL | Endpoint Class | Method Called |
|---|---|---|
/api/v1/article |
ArticleEndpoint |
actionDefault() |
/api/v1/article/detail?id=5 |
ArticleEndpoint |
actionDetail(5) |
/api/v1/user-profile |
UserProfileEndpoint |
actionDefault() |
/api/v1/user-profile/settings |
UserProfileEndpoint |
actionSettings() |
Naming Convention
Endpoint class names are converted to URL paths using kebab-case:
ArticleEndpoint→/api/v1/articleUserProfileEndpoint→/api/v1/user-profileMyAwesomeApiEndpoint→/api/v1/my-awesome-api
Action names also use kebab-case in URLs:
actionGetUserProfile()→/api/v1/endpoint/get-user-profile
:busts_in_silhouette: User Management Integration
The package integrates with baraja-core/cas for user management:
:link: Link Generation
Generate application links from endpoints:
link()- Generates link, throws exception if route doesn't existlinkSafe()- Returnsnullif route doesn't exist
:key: API Token Authentication
For secure communication with external services or partners, use the official token authorizer extension:
structured-api-token-authorizer
:book: Automatic Documentation
Generate API documentation automatically from your endpoint code:
This extension scans your endpoints and generates documentation based on:
- Method signatures and parameters
- PHPDoc annotations
- Return type DTOs
- Permission attributes
:test_tube: Built-in Test Endpoints
The package includes two test endpoints for verification:
Ping Endpoint
Response:
Test Endpoint
Response:
:warning: Error Handling
The API automatically handles errors and returns appropriate HTTP codes:
| HTTP Code | Situation |
|---|---|
| 200 | Successful request |
| 400 | Bad request (validation error) |
| 401 | Unauthorized (not logged in) |
| 403 | Forbidden (missing role) |
| 404 | Endpoint or action not found |
| 500 | Internal server error |
Error response format:
In debug mode (Tracy enabled), the message field contains the actual exception message. In production, a generic error message is shown for security.
:arrows_counterclockwise: CORS Support
Cross-Origin Resource Sharing is automatically handled:
Access-Control-Allow-Origin- Set to request originAccess-Control-Allow-Credentials- EnabledAccess-Control-Max-Age- 86400 seconds (1 day)- OPTIONS preflight requests are handled automatically
:man_technologist: Author
Jan Barasek - https://baraja.cz
:page_facing_up: License
baraja-core/structured-api is licensed under the MIT license. See the LICENSE file for more details.
All versions of structured-api with dependencies
ext-json Version *
ext-mbstring Version *
ext-iconv Version *
baraja-core/service-method-invoker Version ^2.2.1
baraja-core/url Version ^1.1
baraja-core/serializer Version ^1.0
nette/di Version ^3.0
nette/http Version ^3.1
nette/application Version ^3.1
nette/robot-loader Version ^3.3 | ^4.0
nette/caching Version ^3.1