Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    ...
?>
like image 867
Stingus Avatar asked Mar 07 '26 00:03

Stingus


1 Answers

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

like image 141
Ion Bazan Avatar answered Mar 10 '26 00:03

Ion Bazan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!