如何创建不基于实体API平台的资源API?

问题描述 投票:0回答:2

我需要创建一个 GET 端点来返回通过 http 客户端从另一个应用程序获取的资源,而不是基于实体。我获取的资源是一个数组:

[
    "id" => 1234
    "first_name" => ""
    "last_name" => ""
    "email" => ""
    "country" => 1
    "country_code" => 93
    "phone_number" => "3434343"
    "nationality" => "AF"
    "professional_industry" => "Health Care"
    "job_title" => "Medical Doctor - General Practitioner"
    "specialisation" => "No specialisation"
    "career_length_month" => 1
    "career_length_year" => 1
  ]

然后我需要查询数据库以获取一些数据以添加到资源数组中。

所以我在

src/Controller/MyController.php
中创建了它:

    /**
     * @Route("/api/v1/get-profile", name="get_profile")
     * @return JsonResponse
     */
    public function getMemberInfo(): JsonResponse
    {
        // step 1 : use http client to request data from another application
        // step 2 : query DB to fetch some data and add to data array
        return new JsonResponse($data, Response::HTTP_OK);
    }

但是现在,我希望我的 api 返回 json api 响应格式:https://jsonapi.org/.

基于实体的资源,api平台完全支持。我不需要做太多事。我只是在实体类中添加“key”

#[ApiResource]
并配置一些东西。然后我就有了一个json api格式的api,如此简单:

{
    "data": {
        "id": "",
        "type": "",
        "attributes": {}
    }
}

但是不基于实体的资源怎么样?有没有我可以使用的 api-platform 的内置功能,或者我必须自己做一个转换器?

symfony api-platform.com
2个回答
1
投票

您需要覆盖文档中描述的 OpenAPI 规范: https://api-platform.com/docs/core/openapi/#overriding-the-openapi-specification

然后,在新类中,您必须添加所需的架构定义,添加新的 PathItem 实例,每个 PathItem 需要新的 Operation 实例等。

抱歉没有粘贴示例,它需要这么多代码。我在一个项目中就是这样工作的,但目前还没有公开。

我希望我能阻止你。


0
投票

好的做法是创建自定义数据提供程序。此自定义状态提供程序将负责从外部源获取数据。然后,API 平台将能够像常规实体一样使用它。

© www.soinside.com 2019 - 2024. All rights reserved.