usox / json-schema-api
为 PHP 开发的 JSON schema 驱动的 API 创建
Requires
- php: ^8.1
- ext-json: *
- opis/json-schema: ^2.1
- php-http/discovery: ^1.13
- psr/http-factory: ^1.0
- psr/http-message: ^1||^2
- psr/http-server-handler: ^1.0
- psr/log: ^1.1||^3
- ramsey/uuid: ^4.1
- shrikeh/teapot: ^2.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- laminas/laminas-diactoros: ^3
- mikey179/vfsstream: ^1.6
- mockery/mockery: ^1.4
- phpstan/phpstan: ^1
- phpstan/phpstan-mockery: ^1
- phpstan/phpstan-strict-rules: ^1
- phpunit/phpunit: ^10
- rector/rector: ^0.18
README
JsonSchemaApi
这个库提供了一个简单的方法来使用 json-schema 验证请求来创建 JSON API。您可以将大多数输入验证任务(变量类型、长度/内容约束、仅包含特定项的列表等)利用到 JSON schema 验证器中,并立即与数据一起工作。
Json-Schema
每个方法都需要一个对应的 schema 文件,该文件描述了请求数据应该如何看起来。您可以在 example/schema
文件夹中找到一个简单的示例。
每个请求也必须遵循一个基本 schema(见 dist/request.json
),其中包含有关方法的信息。
验证
每个请求和生成的响应都将与提供的 schema 进行验证。
要求
此库需要现有的 psr7 和 psr17 实现。
安装
composer require usox/json-schema-api
用法
只需使用工厂方法创建端点。工厂会自动搜索现有的 psr17 流工厂实现,但您也可以在调用方法时提供工厂实例。
准备您的提供者方法(见下文),并在端点上调用 factory
方法以获取一个可工作的实例
serve 方法需要一个 psr 请求并返回一个 psr 响应。
$endpoint = \Usox\JsonSchemaApi\Endpoint::factory( $methodProvider ); $endpoint->serve( $psr7Request, $psr7Response );
可选:PSR15 中间件
端点类实现了 PSR15 RequestHandlerInterface
。
方法提供者
MethodProvider
是您 API 方法的来源 - 这可以是简单的数组、DI 容器等。该类必须实现 Usox\JsonSchemApi\Contract\MethodProviderInterface
。
class MyMethodProvider implements \Usox\JsonSchemaApi\Contract\MethodProviderInterface { private array $methodList = ['beerlist' => BeerlistMethod::class]; public function lookup(string $methodName) : ?\Usox\JsonSchemaApi\Contract\ApiMethodInterface { $handler = $this->methodList[$methodName] ?? null; if ($handler === null) { return null; } return new $handler; } }
API 方法
方法提供者的 lookup
方法必须返回 Usox\JsonSchemaApi\Contract\ApiMethodInterface
的实例。
每个 API 方法处理程序必须定义至少以下两个方法
handle
方法,它处理请求并返回结果getSchemaFile
方法,它返回用于验证请求的 schema 文件的路径
class BeerlistMethod implements \Usox\JsonSchemaApi\Contract\ApiMethodInterface { public function handle(stdClass $parameter) : array { return ['ipa', 'lager', 'weizen']; } public function getSchemaFile() : string { return '/path/to/schema.json'; } }
示例
您可以在 example
文件夹中找到一个可工作的示例。
只需切换到 example 文件夹并启动 PHP 内置的 web 服务器 php -S localhost:8888
。现在您可以使用 curl 发送类似这样的 API POST
请求。
curl -X POST -d '{"method": "beerlist", "parameter": {"test1": "foobar", "test2": 666}}' "http://localhost:8888"
错误处理
基本上有三种类型的错误。所有这些都会被记录。
ApiExceptions
如果处理程序抛出一个扩展 ApiException
异常类的异常,则 API 将返回一个包含错误消息(异常消息)和错误代码的 JSON 响应的 Bad Request (400)
响应。
InternalException
内部错误,如不存在的 schema 文件、无效的 schema 等,将返回一个 Internal Server Error (500)
响应,并创建一个日志条目(如果提供了记录器)。
此外,异常中的可选上下文信息也将被记录。
Throwable
在 API 处理程序中抛出的任何 Throwable 都将被捕获、记录并返回一个 Internal Server Error (500)
响应。