REST API 应该选择 ID 还是名称字段? [英] Should a REST API select on a ID or a name field?

查看:29
本文介绍了REST API 应该选择 ID 还是名称字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个 REST API 并试图确定哪种返回单个资源的更正确方式:

I'm designing a REST API and trying to decide which is the more correct way of returning a single resource:

/resource/{id}

/resource/{name}

ID 是不可变的,所以我认为通过它选择会更好,但名称看​​起来会更友好.最佳做法是什么?我在野外"之前见过两者都使用过.

The ID would be immutable, so I'm thinking that it would be better to select by it, but name would be more friendly looking. What is the best practice? I've seen both used before "in the wild".

推荐答案

基本上 REST 建立在唯一 ID 之上,因此:

Basically REST is built on top of unique IDs, thus:

GET    /resources/{id}/

应该使用.但是,没有什么可以阻止您使 name 字段唯一(现在它表现为普通的旧 ID)并在此唯一 ID 之上构建 REST.

should be used. However, there's nothing that prevents you from making name field unique (now it behaves as plain old ID) and build REST on top of this unique ID.

如果这不是您所需要的并且 name 不能唯一,那么另一种选择是通过 name 实现过滤:

If this is not what you need and name cannot be made unique, then another option is to implement filtering via name:

GET    /resources?name=<SOME_NAME>

它也应该是 resources(复数),因为它表明在幕后有一个集合.

It also should be resources (plural) since it indicates that there's a collection under the hood.

这篇关于REST API 应该选择 ID 还是名称字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆