php - 如何在 API 平台中创建自定义端点并将其添加到文档中?

标签 php rest symfony api-platform.com

我想创建未映射的实体端点,如 /api/v1/me 返回有关当前已验证用户的信息(User 对象)并将其添加到我的文档中.在计划中,我还想添加 /api/v1/account/recover/api/v1/account/verify-email 等端点。

我有一个 Action :

namespace AppBundle\Action\Me;

use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class MeView
{

    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @Security("is_authenticated()")
     *
     * @Route(
     *     name="me_view",
     *     path="/me",
     *     methods={"GET"}
     * )
     *
     * @return User
     */
    public function __invoke()
    {
        return $this->tokenStorage->getToken()->getUser();
    }
}

但是当我尝试访问它时,它返回一个异常:

The controller must return a response (Object(AppBundle\Entity\User) given). (500 Internal Server Error)

相同的操作,但与实体映射,效果很好:

namespace AppBundle\Action\City;

use AppBundle\Entity\City;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;

class CityView
{

    /**
     * @Security("is_authenticated()")
     *
     * @Route(
     *     name="city_view",
     *     path="/cities/{id}",
     *     methods={"GET"},
     *     defaults={"_api_resource_class"=City::class, "_api_item_operation_name"="view"}
     * )
     *
     * @param City $city
     * @return City
     */
    public function __invoke(City $city)
    {
        return $city;
    }
}

我应该怎么做才能使我的自定义操作起作用以及如何将其添加到自动生成的 Swagger 文档中?

最佳答案

Controller :

class MyUserController extends  Controller
{
    public function fn_me()
    {
        return $this->getUser();
    }
}

实体:

 * @ApiResource(
 *  collectionOperations={
 *      "get","post",
 *      "collName_api_me"={"route_name"="api_me"}
 *  }
 * )
 */
class User implements UserInterface, \Serializable

路由.yaml

api_me:
    path: '/api/me'
    methods: ['GET']
    defaults:
        _controller: '\App\Controller\MyUserController::fn_me'
        _api_resource_class: 'App\Entity\User'
        _api_collection_operation_name: 'collName_api_me'

关于php - 如何在 API 平台中创建自定义端点并将其添加到文档中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44926811/

相关文章:

php - 只需传递视频 URL 即可播放 Youtube 视频

php - 将 url service.php?p_id=1&s_id=4 重写为 service/seo

node.js - 无法访问中间件内的 req.body

java - 对本地选项集的 InsertOptionValue 操作

symfony - 获取所有 Twig 模板的列表 Symfony

php - 包含绝对/相对定位的 2 列布局的 CSS

ajax - Grails - Spring Security REST - 302 响应 net::ERR_TOO_MANY_REDIRECTS

php - 将 php 数组转发到 twig 模板 (Symfony)

php - Symfony 2.6/Doctrine ORMException : The EntityManager is closed

javascript - 在javascript中获取多个 "contenteditables"的值