redrat / api-helper-bundle
Requires
- php: >=7.4
- ext-json: *
- fig/http-message-util: ^1.1
- symfony/framework-bundle: ^4.4 || ^5.0
- symfony/yaml: ^4.4 || ^5.0
Requires (Dev)
- mockery/mockery: ^1.4
- phpunit/phpunit: ^9.2
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-13 18:28:24 UTC
README
这个Symfony扩展提供配置,以验证和转换API路由的数据。
首先,为什么需要它?
因为我需要一个具有可配置URL前缀的扩展,用作API路由。在Symfony中默认情况下,只有内容类型为multipart/form-data
和application/x-www-form-urlencoded
的请求,请求类中的参数数据可以通过get()
方法轻松访问,如下例所示。
class MyController { public function handleForm(Request $request): Response { $myName = $request->get('myName'); // return Joubert RedRat } public function handleApi(Request $request): Response { $myName = $request->get('myName'); // return null } }
使用此扩展,可以配置哪些路由作为API路由,并且任何内容类型为application/json
的请求也将能够轻松访问请求类中的参数数据。
那么如何安装呢?
很简单,使用composer进行安装。
composer require redrat/api-helper-bundle
配置扩展(如有必要)
如果你的composer不喜欢Symfony recipes contrib,不要担心,你也可以进行配置。
- 打开
config/bundles.php
并在其中添加扩展,如下所示。
return [ Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], RedRat\ApiHelperBundle\ApiHelperBundle::class => ['all' => true], ];
- 创建
config/packages/redrat_api_helper.yaml
并设置初始配置,如下所示。
redrat_api_helper: paths:
扩展如何工作?
此扩展通过config/packages/redrat_api_helper.yaml
中定义的配置进行工作。在这个文件中,您将配置哪些URL路径前缀将作为API URL工作,如下例所示
redrat_api_helper: paths: my_amazing_api_v1: url_path_prefix: /api/v1 other_api_v3: url_path_prefix: /api/v3 old_not_cute_api: url_path_prefix: /legacy/api
您可以根据需要配置一个或多个URL路径前缀。
之后,所有与配置匹配的URL路径都将由扩展处理,并验证数据并将其放入请求类。
请注意,只有与配置匹配的路由才会被扩展处理,如下例所示使用上述配置。
GET /api/v1/accounts/users => matches
POST /api/login => doesn't matches
DELETE /api/v2/emails => doesn't matches
PUT /api/v1/accounts/users/46 => matches
PATCH /api/v1/accounts/users => matches
GET /about-us => doesn't matches
GET /legacy/api/v1/cities => matches
验证
此扩展在匹配配置的路由中执行2个验证。
内容类型
匹配的路由应具有application/json
作为Content-Type,方法为POST
、PUT
和PATCH
。如果不通过此验证,扩展将返回以下错误。方法GET
和DELETE
通常不包含正文数据,因此这些方法不进行验证。
< HTTP/2 400
{
"error": "Invalid Content-Type, expected application\/json, got application\/x-www-form-urlencoded"
}
有效的JSON数据
匹配的路由应在正文中具有有效的RFC7159 JSON数据。如果不通过此验证,扩展将返回以下错误。
< HTTP/2 400
{
"error": "Invalid json body data"
}
作者
许可
可爱的MIT。