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

查看:124
本文介绍了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天全站免登陆