Search code examples
apisymfonyjson-ldapi-platform.comhydration

How rename the @id in Json ld Context - API Platform [Resolved]



I am working for an API and I have a problem with my Json-ld
Is it possible to change the @id in the Json-ld Context ?

Entity :

/**
 * @ApiResource(
 *      normalizationContext={"groups"={"question_get"}},
 *      denormalizationContext={"groups"={"question_post"}},
 *      itemOperations={
 *          "get" = {
 *              "enable_max_depth"=true,
 *              "force_eager"=false,
 *          },
 *          "put" = {
 *               "denormalization_context"={"groups"={"question_put"}}
 *          }
 *      },
 *      collectionOperations={
 *          "get"= {
 *                   "normalization_context"={"groups"={"questions_get"}},
 *               },
 *          "post"
 *      },
 *      attributes={
 *          "enable_max_depth"="true",
 *          "pagination_client_items_per_page"=true,
 *      },
 *  )
 */
class Question
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

  ...

Json :

"@context": "/api/contexts/Question",
  "@id": "/api/questions",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/questions/32",
      "@type": "Question",
      "id": 32,
     ...

And what I Want :

  "@id": "/questions"

I want to keep route "/api/question", I'm only looking for change the @id of my entity but not relation.

Edit: I found a way, I use a normalizer : https://api-platform.com/docs/core/identifiers/#custom-identifier-normalizer

#App\src\Serializer\ApiNormalizer.php

...

 public function normalize($object, $format = null, array $context = [])
    {

        $data = $this->decorated->normalize($object, $format, $context);

        $data['@id'] = substr($data['@id'], 4);

        return $data;

    }

...


Solution

  • You can provide an alias/shortening in your context:

    "type" : "@type",
    "id" :"@id"
    

    This allows you to get rid of @-signs in your documents and in your code. read more