web-dev-qa-db-ja.com

APIプラットフォームでカスタムエンドポイントを作成してドキュメントに追加するにはどうすればよいですか?

現在認証されているユーザーに関する情報(Userオブジェクト)を返す/api/v1/meのようなエンティティエンドポイントにマップされていないものを作成し、それをドキュメントに追加したいと思います。プランでは、/api/v1/account/recover/api/v1/account/verify-emailなどのエンドポイントも追加したいと思います。

私には行動があります:

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();
    }
}

しかし、アクセスしようとすると、例外が返されます。

コントローラは応答を返す必要があります(Object(AppBundle\Entity\User)が指定されています)。 (500内部サーバーエラー)

同じアクションですが、エンティティにマップされており、うまく機能します。

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ドキュメントに追加するにはどうすればよいですか?

4
Petr Flaks

まず、それを機能させるために、それがエンティティにリンクされていない場合は、JsonResponseを返す必要があります。

そして多分あなたはこのようなものをすることができます: https://github.com/api-platform/api-platform/issues/246#issuecomment-287638334

0
Hamza Amrouche