首页 > 解决方案 > 在 API Post 方法中引用相关资源

问题描述

我正在创建一个创建帖子的 API 端点:

POST > /posts

每个帖子最多可以有一个类别和多个标签。

创建帖子时,我需要引用其类别和标签(如果有):

  1. 要引用类别,通常我会发送 CategoryId;
  2. 为了引用标签,我通常会发送标签名称,因为其中一些可能是新的。

所以我的 Json 会是这样的:

{
  "title": "Some title",
  "content": "Some content",
  "categoryId": 1,
  "tagsNames": ["adventure", "drama"]
}

或者我应该允许,作为一个选项,按名称引用类别和按 ids 标记:

{
  "title": "Some title",
  "content": "Some content",
  "categoryName": "books",
  "tagsIds": [1, 2]
}

为了没有不同的端点,我可以使用以下内容:

{
  "title": "Some title",
  "content": "Some content",
  "category": {
    "id": 1,
    "name": null
  },
  "tags": [
    {
      "id": null,
      "name": "adventure"
    },
    {
      "id": null,
      "name": "drama"
    }
  ]
}

然后后端确定如何引用类别和标签:通过 id 或名称。

有这方面的标准吗?

标签: jsonapiasp.net-coreapi-design

解决方案


有这方面的标准吗?

嗯,这没有标准。选择对您的 API 更有意义的方法,并确保其属性已记录在案。

但是一旦你代表了一种关系,使用 id 就很有意义。如果名称是唯一的(并且它们不会更改),则它们可用于标识您的资源。


推荐阅读