API 平台不可变 属性
API Platform immutable property
我在 Symfony 4.3 项目上使用 API 平台,我只想拥有一个不可变的 属性(在本例中为 userId
),可以在 POST 但不能用 PUT 更改。到目前为止,完成此操作的唯一方法是删除 userId
setter 并使用构造函数来初始设置值。
此设置仍然显示 属性 in Swagger for PUT(下图),但更麻烦的是它在不修改记录的情况下接受 属性。这是一个沉默的忽略,我更喜欢 400 Bad Request return 代码让客户知道他的请求没有按预期处理。
有没有其他方法可以通过 API 平台实现类似的行为?已经尝试过序列化组,但可能设置有误。
<?php
declare(strict_types = 1);
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\NumericFilter;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SubscriptionRepository")
*
* @UniqueEntity("userId")
*
* @ApiResource()
*/
class Subscription
{
/**
* @var int
*
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var int
*
* @ORM\Column(type="integer")
*
* @ApiFilter(NumericFilter::class)
*/
private $userId;
/**
* Subscription constructor.
*
* @param int $userId
*/
public function __construct(int $userId)
{
$this->userId = $userId;
}
...
?>
我认为您需要将 PUT 请求的 normalization_context.groups
显式设置为 {"read"}
(或其他设置,具体取决于您的配置)。
参见 Operations documentation
我在 Symfony 4.3 项目上使用 API 平台,我只想拥有一个不可变的 属性(在本例中为 userId
),可以在 POST 但不能用 PUT 更改。到目前为止,完成此操作的唯一方法是删除 userId
setter 并使用构造函数来初始设置值。
此设置仍然显示 属性 in Swagger for PUT(下图),但更麻烦的是它在不修改记录的情况下接受 属性。这是一个沉默的忽略,我更喜欢 400 Bad Request return 代码让客户知道他的请求没有按预期处理。
有没有其他方法可以通过 API 平台实现类似的行为?已经尝试过序列化组,但可能设置有误。
<?php
declare(strict_types = 1);
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\NumericFilter;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SubscriptionRepository")
*
* @UniqueEntity("userId")
*
* @ApiResource()
*/
class Subscription
{
/**
* @var int
*
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var int
*
* @ORM\Column(type="integer")
*
* @ApiFilter(NumericFilter::class)
*/
private $userId;
/**
* Subscription constructor.
*
* @param int $userId
*/
public function __construct(int $userId)
{
$this->userId = $userId;
}
...
?>
我认为您需要将 PUT 请求的 normalization_context.groups
显式设置为 {"read"}
(或其他设置,具体取决于您的配置)。
参见 Operations documentation