appaydin / pd-api

Symfony Restful Api Bundle

1.0.03 2021-06-09 18:13 UTC

This package is auto-updated.

Last update: 2024-09-05 00:28:06 UTC


README

Symfony 5 Restful Api Bundle

Packagist Github Release license PHP from Packagist

  • 支持XML和JSON响应
  • 错误消息以单一格式收集。
  • 所有错误消息都应用了语言翻译。
  • 添加了请求体转换器(JSON-XML)。
  • 为表单错误添加了规范化器。
  • 为KnpPaginator添加了规范化器。

安装

步骤1:下载Bundle

打开命令控制台,进入您的项目目录,并执行以下命令以下载此bundle的最新稳定版本

composer require appaydin/pd-api

此命令要求您全局安装Composer,具体请参阅Composer文档中的安装章节

步骤2:启用Bundle

在Symfony 5中,包将被自动激活。但如果出现问题,您可以手动安装。

然后,通过将其添加到项目config/bundles.php文件中注册的Bundle列表中来启用该bundle。

<?php
// config/bundles.php

return [
    //...
    Pd\ApiBundle\PdApiBundle::class => ['all' => true]
];

步骤3:设置Bundle

# config/packages/pd_api.yaml

pd_api:
    zone: ["^/api"]
    default_accept: json
    default_groups: ['default']
    allow_accept: ['json', 'xml']

步骤4:设置Security.yaml

# config/packages/security.yaml

security:
  providers:
    ...
    pdadmin_api:
      entity:
        class: App\Entity\User
        property: phone
  firewalls:
    ...
    api:
      pattern: ^/api
      stateless: true
      anonymous: true
      provider: pdadmin_api
      json_login:
        check_path: /api/auth/login
        failure_handler: lexik_jwt_authentication.handler.authentication_failure
      guard:
        authenticators:
          - lexik_jwt_authentication.jwt_token_authenticator
  access_control:
    - { path: ^/api/auth, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

步骤5(可选):创建登录端点

# src/Controller/AuthorizationController.php

namespace App\Controller;

use Pd\ApiBundle\Controller\AbstractApiController;
use Pd\ApiBundle\Controller\LoginTrait;

class AuthorizationController extends AbstractApiController
{
    use LoginTrait;
}
# config/routes.yaml
api:
  resource: ../src/Controller
  type: annotation
  prefix: api

创建API

# src/Controller/ExampleApiController.php

use Pd\ApiBundle\Controller\AbstractApiController;
use Symfony\Component\Routing\Annotation\Route;

class ExampleApiController extends AbstractApiController
{
    #[Route("/home", name:"api.home", methods: ["GET"])]
    public function home() {
        return ['test'];
    }
}