Stingus
Stingus

Reputation: 358

API Platform immutable property

I'm using API Platform on a Symfony 4.3 project and I just want to have an immutable property (userId in this case) which can be set on POST but cannot be changed with PUT. So far, the only way to accomplish this was to drop the userId setter and use the constructor to initially set the value.

This setup still shows the property in Swagger for PUT (image below), but more troublesome is that it accepts that property without modifying the record. It's a silenced ignore and I would prefer a 400 Bad Request return code to let the client know his request was not processed as expected.

enter image description here

Is there any other way I could accomplish a similar behavior with API Platform? Already tried serialization groups, maybe with the wrong settings though.

<?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;
    }

    ...
?>

Upvotes: 3

Views: 1032

Answers (1)

Ion Bazan
Ion Bazan

Reputation: 838

I think you will need to explicitly set normalization_context.groups for PUT request to {"read"} (or something else, depending on your configuration). See Operations documentation

Upvotes: 3

Related Questions