Having property of a same class in Symfony ApiPlatform

Viewed 260

I have gone over the ApiPlatform SymfonyCasts and so far I love what I can do with it. However, I have hit the wall with the following scenario:

  • I have a class Contract with property baseContract which points to an object on which the new object should be based upon.

  • Both denormalizationContext and normalizationContext are set for all fields (for now) to contracts:write and contracts:read, respectfully.

  • When I go to /api, both GET and POST endpoints show all properties, but skip the baseContract...

Is there some gotcha to this?

The very basic idea is that I want to be able to post something like this:

{
  "name": "string",
  "description": "string",
  "contractNo": "string",
  "baseContract": "/api/contacts/{some_id}
}
    /**
     * @ORM\Entity(repositoryClass=ContractRepository::class)
     *
     * @ApiResource(
     *     normalizationContext={"groups": "contract:read"},
     *     denormalizationContext={"groups": "contract:write"},
     *     collectionOperations={
     *          "get",
     *          "post"
     *     },
     *     itemOperations={
     *          "get"
     *     }
     * )
     */
    class Contract
    {
......
        /**
         * @ORM\ManyToOne(targetEntity=Contract::class)
         * @ORM\JoinColumn()
         *
         * @Groups({"contract:read", "contract:write"})
         */
        private ?Contract $baseContract;
1 Answers

I have finally checked on my projet. As you said in the comments, it's indeed because of the recursion.

With this serialization groups configuration, you're embedding your baseContract property.

Add an annotation @ApiProperty(readableLink=false, writableLink=false) to the $baseContract. It prevents the embedding behaviour and the swagger should display your field.

Related