frootbox/rest-api
最新稳定版本:0.5.6
Composer 安装命令:
composer require frootbox/rest-api
包简介
Frootbox REST API Framework
README 文档
README
A lightweight, attribute-based REST API framework for PHP.
This package provides a simple way to build versioned REST APIs with support for multiple authentication methods like API keys, Bearer tokens, Basic Auth, and custom client credentials.
✨ Features
- Attribute-based routing (OpenAPI compatible)
- API versioning via namespace (
V1,V2, ...) - Multiple authentication methods:
- API Key
- Bearer (JWT)
- Basic Auth
- Client credentials
- Dependency Injection support (PHP-DI)
- Automatic route discovery
- Named route parameters (
{id},{int:id}) - JSON response handling
📦 Installation
composer require frootbox/restapi
🚀 Getting Started
1. Create a Server instance
use Frootbox\\RestApi\\Server; use DI\\Container; $container = new Container(); $server = new Server( clientRepository: $clientRepository, // implements ClientRepositoryInterface baseUriRegex: '#^/api/v(?P<Version>[0-9]+)(?P<Path>/.*)$#', controllerDirectory: __DIR__ . '/Controller', namespace: 'App\\\\Controller', container: $container, hashKey: 'your-secret-key' ); $server->execute();
📁 Controller Structure
Controllers must follow a versioned namespace structure:
src/
└── Controller/
└── V1/
└── UserController.php
🧩 Example Controller
namespace App\\Controller\\V1; use OpenApi\\Attributes as OA; use Frootbox\\RestApi\\Attribute\\Auth; use Frootbox\\RestApi\\Attribute\\ApiKey; use Frootbox\\RestApi\\Response\\Payload; class UserController { #[OA\\Get(path: '/users/{int:id}')] #[Auth(type: new ApiKey())] public function getUser(int $id): Payload { return new Payload([ 'id' => $id, 'name' => 'John Doe' ]); } }
🔐 Authentication
You can define one or multiple authentication methods per endpoint:
#[Auth(type: new ApiKey())] #[Auth(type: new Bearer())]
Supported Auth Methods
API Key
Send via header:
x-api-key: your-api-key
Bearer Token (JWT)
Authorization: Bearer <token>
Basic Auth
Authorization: Basic base64(clientId:clientSecret)
Client Credentials (GET or Basic)
GET /endpoint?client_id=xxx&client_secret=yyy
or via Basic Auth.
🧠 Client Validation
You must provide a repository implementing:
Frootbox\\RestApi\\Interface\\ClientRepositoryInterface
Example:
class ClientRepository implements ClientRepositoryInterface
{
public function validate(string $clientId, string $clientSecret): void
{
if ($clientId !== 'test' || $clientSecret !== 'secret') {
throw new \\Exception('Invalid client credentials');
}
}
public function validateApiKey(string $apiKey): void
{
if ($apiKey !== 'abc123') {
throw new \\Exception('Invalid API key');
}
}
}
🔄 Versioning
API version is extracted from the URL:
/api/v1/users/1
Your controllers must match the version namespace:
namespace App\\Controller\\V1;
🧾 Route Parameters
Integer parameter
/users/{int:id}
String parameter
/users/{slug}
ULID parameter
/users/{ulid:id}
OpenAPI parameter pattern
#[OA\Get(path: '/users/{id}')] #[OA\Parameter( name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'string', pattern: '^[0-9A-HJKMNP-TV-Z]{26}$'), )]
Static routes are matched before dynamic routes, so /users/search is preferred over /users/{id} regardless of reflection order.
Parameters are automatically injected into the method.
📤 Responses
All responses must return:
Frootbox\\RestApi\\Response\\Payload
Example:
return new Payload([ 'success' => true ]);
⚙️ Dependency Injection
Controllers are resolved via the provided DI container:
$container->call([$controller, $method]);
You can inject services directly into controller methods:
public function getUser(UserService $service, int $id)
🔧 Hooks
Token decoding hook
$server = new Server(..., onDecodeToken: function ($token) {
// custom logic
});
Client validation hook
$server = new Server(..., onValidateClient: function ($clientId) {
// custom logic
});
⚠️ Important Notes
- Always use HTTPS when transmitting credentials
- API keys should be treated like passwords
- Bearer tokens are validated using HS256
- Route matching is case-insensitive
📄 License
MIT """
frootbox/rest-api 适用场景与选型建议
frootbox/rest-api 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 553 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 09 月 21 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 frootbox/rest-api 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 frootbox/rest-api 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 553
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: GPL-3.0-or-later
- 更新时间: 2024-09-21