gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:51:05 25 4
gpt4 key购买 nike

我想创建未映射的实体端点,如 /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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com