json - 在 API Post 方法中引用相关资源
问题描述
我正在创建一个创建帖子的 API 端点:
POST > /posts
每个帖子最多可以有一个类别和多个标签。
创建帖子时,我需要引用其类别和标签(如果有):
- 要引用类别,通常我会发送 CategoryId;
- 为了引用标签,我通常会发送标签名称,因为其中一些可能是新的。
所以我的 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 或名称。
有这方面的标准吗?
解决方案
有这方面的标准吗?
嗯,这没有标准。选择对您的 API 更有意义的方法,并确保其属性已记录在案。
但是一旦你代表了一种关系,使用 id 就很有意义。如果名称是唯一的(并且它们不会更改),则它们可用于标识您的资源。
推荐阅读
- python - 如何以非唯一方式选择随机字符
- c++ - nullptr 检查链接成员指针访问
- awk - 在转置期间处理不存在的条目
- nlp - NLTK 词性标签是否将“apps”和“please”视为动词?
- javascript - 如何使用 cypress 在网页上运行 javascript
- mailchimp - Mailchimp:是无效的电子邮件地址,无法导入
- angular - 当我对具有 100-200 条记录的 Angular Material 数据表的分页器值进行排序或更改时,页面冻结
- amazon-web-services - 用于多种服务的无服务器 AWS 同一层
- ios - 具有 0.5 高度约束的多个 UIView 未以相同方式呈现
- swiftui - 使用 ToolbarItemGroup 时项目之间的空间太大