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

查看:32
本文介绍了在 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 实体

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

我想返回一个基于该产品实体但带有自定义字段的 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';
    }
}

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

You might need to use the serialization groups too.

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

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.

如果你需要更细粒度的控制,你也可以hook一个(或多个)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天全站免登陆