在API平台上返回自定义JSON的最佳做法 [英] Best practice to return custom JSON on API-platform

查看:96
本文介绍了在API平台上返回自定义JSON的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新现有的API(使用FOSRest创建).

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

我有很多返回自定义JSON对象的路由,这些路由与我的实体不同.

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

例如,我有一个 Offer 实体

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

我想返回一个基于该产品实体但具有自定义字段的JSON对象.

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

为该GET方法创建新资源真的是强制性的吗,还是有最佳实践呢?

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

推荐答案

有多种添加自定义数据的方法:

There is multiple ways to add custom data :

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

您可能需要使用序列化组.

如果您的自定义数据需要从实体外部提取:此处是文档

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

它会覆盖默认的 Serializer 服务(在发送响应之前调用),并允许您向每个请求添加额外的数据(从任何位置).

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.

如果您需要更多细粒度的控制,还可以使用一个(或多个)api平台事件.

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.

这篇关于在API平台上返回自定义JSON的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆