【问题标题】:API Platform - How to Use a DTO for Posting?API 平台 - 如何使用 DTO 进行发布?
【发布时间】:2018-11-18 13:07:14
【问题描述】:

我在我的 Symfony4 应用程序中使用 API 平台来公开我的资源。 这是一个很棒的框架,但默认情况下它会强制您将所有业务逻辑都放在前端,因为它公开了您的所有实体而不是业务对象。

我不喜欢这样,我更喜欢将我的业务逻辑放在后端。

我需要创建用户,但是有不同类型的用户。 所以我在后端创建了一个 UserFactory 。所以前端只需要推送一个业务对象,后端处理一切。

前端永远不能直接在数据库中持久化用户对象。是后端的作用

按照本教程使用 DTO 进行阅读: https://api-platform.com/docs/core/dto/#how-to-use-a-dto-for-reading

我正在尝试为发帖做同样的事情。它有效。这是我的控制器代码:

/**
 * @Route(
 *     path="/create/model",
 *     name="create-model",
 *     methods={"POST"},
 *     defaults={
 *          "_api_respond"=true,
 *          "_api_normalization_context"={"api_sub_level"=true},
 *          "_api_swagger_context"={
 *              "tags"={"User"},
 *              "summary"="Create a user Model",
 *              "parameters"={
 *                  
 *              },
 *              "responses"={
 *                  "201"={
 *                      "description"="User Model created",
 *                      "schema"={
 *                          "type"="object",
 *                          "properties"={
 *                              "firstName"={"type"="string"},
 *                              "lastName"={"type"="string"},
 *                              "email"={"type"="string"},
 *                          }
 *                      }
 *                  }
 *              }
 *          }
 *     }
 * )
 * @param Request $request
 * @return \App\Entity\User
 * @throws \App\Exception\ClassNotFoundException
 * @throws \App\Exception\InvalidUserException
 */
public function createModel(Request $request)
{
    $model = $this->serializer->deserialize($request->getContent(), Model::class, 'json');
    $user = $this->userFactory->create($model);
    $this->userRepository->save($user);

    return $user;
}

效果很好,但我希望我的新资源能够在 Swagger UI 中工作,因此我可以直接在 Web 界面中通过 POST 方法创建新资源。

为此,我认为我需要在我的 _api_swagger_context 中完成参数部分。但我没有找到任何关于此的文档。

我该怎么做?

【问题讨论】:

  • "默认情况下你所有的业务逻辑都在前端......"这不是真的,你可以在symfony/doctrine events里面做业务逻辑。
  • @IwanWijaya 我知道。我只是在谈论业务对象。

标签: symfony swagger swagger-ui symfony4 api-platform.com


【解决方案1】:

在这里找到答案:https://github.com/api-platform/docs/issues/666

你可以像这样填写参数:

 "parameters" = {
     {
        "name" = "data",
        "in" = "body",
        "required" = "true",
        "schema" = {
            "type" = "object",
            "properties" = {
                 "firstName"={"type"="string"},
                 "lastName"={"type"="string"},
                 "email" = {"type" = "string" }
             }
         },
     },
 },

更多关于 swagger 参数的文档:https://swagger.io/docs/specification/2-0/describing-parameters/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2017-03-20
    相关资源
    最近更新 更多