Best practice to return custom JSON on API-platform

流过昼夜 提交于 2019-12-13 08:49:01

问题


I want to update my existing API (created with FOSRest).

I have lots of routes that return custom JSON objects, different from my entities.

For example, I have an Offer entity

<?php
// api/src/Entity/Offer.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * An offer from my shop - this description will be automatically extracted form the PHPDoc to document the API.
 *
 * @ApiResource(iri="http://schema.org/Offer")
 * @ORM\Entity
 */
class Offer
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @ORM\Column(type="text")
     */
    public $description;

    /**
     * @ORM\Column(type="float")
     * @Assert\NotBlank
     * @Assert\Range(min=0, minMessage="The price must be superior to 0.")
     * @Assert\Type(type="float")
     */
    public $price;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="offers")
     */
    public $product;
}

And I want to return a JSON object based on that product entity but with custom fields.

Is it really mandatory to create a new resource just for that one GET method or is there a best practice to do that?


回答1:


There is multiple ways to add custom data :

(simplest) Add a custom entity method

class Offer
{
    public function getSomethingCustomized() 
    {
        return 'something_customized';
    }
}

You might need to use the serialization groups too.

Decorate the serializer

If your custom data needs to be pulled from outside the entity : Here is the documentation

It overrides the default Serializer service (called before sending the response), and allow you to add extra data (from wherever you want) to each request.

Use events

If you need more fine-grained control, you can also hook on one (or more) api-platform event.

I personally use this method to reconcile external relations (not persisted by doctrine) on (persisted) entities.



来源:https://stackoverflow.com/questions/52540768/best-practice-to-return-custom-json-on-api-platform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!