在 REST API 中使用另一个资源的 id 命名获取资源 [英] Getting a resource using another resource's id naming in REST API

查看:39
本文介绍了在 REST API 中使用另一个资源的 id 命名获取资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义 REST API,但不确定如何命名端点.

我已经有了以下方法

GET/users/{user_id}

这将返回以下内容:

<代码>{"user_id": "一些 id",用户名":一些用户名(与 user_id 1:1)",...}

我想要一个端点通过 username 检索资源,但我不确定它是否应该

GET/users/username/{username}

或者更确切地说

GET/usernames/{username}/user

还是别的?

解决方案

通常资源由一个标识符唯一标识.在您的情况下,这将是 user_id.因此,如果 user_id 是您系统中唯一标识用户的内容,那么您的 GET/users/{user_id} RESTful 路由就非常有意义.

另一方面,如果您想通过其他一些条件(例如 username)搜索用户,您可以只使用查询字符串参数:

GET/users?username=foo_bar

这显然会返回一组用户名与此条件匹配的用户,如果在您的情况下用户名是唯一的,则此数组将始终最多包含一个元素:

<预><代码>[{用户 ID":123,用户名":foo_bar"}]

另一方面,如果您确定 user_id 是系统中 user 资源的某个内部系统标识符(例如,它可能是 SQL 中的主键)数据库)并且您想在您的 RESTful 外观中向用户公开一些更友好的唯一 ID,那么您可以考虑使用 GET/users/{username}.当然,在这种情况下,您应该很好地定义 username 是什么以及它允许​​的字符是什么,因为如果您在用户名中允许一些特殊字符,事情可能很快就会变成一场噩梦.这是一个 很好地阅读了关于这个主题的内容,我强烈建议您阅读并很好地理解 URL 路径段中允许使用的字符.

I am defining a REST API and am not sure about naming an endpoint.

I have the following method already

GET /users/{user_id}

This returns the following:

{
    "user_id": "some id",
    "username": "some username (1:1 with user_id)",
    ...
}

I want an endpoint to retrieve the resource by username, and I am not sure if it should be

GET /users/username/{username}

or rather

GET /usernames/{username}/user

or something else?

解决方案

Usually a resource is uniquely identified by one single identifier. In your case that would be the user_id. So your GET /users/{user_id} RESTful route makes perfect sense if the user_id is what uniquely identifies a user in your system.

On the other hand if you want to be searching users by some other criteria (like a username) you could just use query string parameters:

GET /users?username=foo_bar

which will obviously return an array of users whose username matches this criteria and if in your case the username is unique this array will always contain at most one element:

[
    {
        "user_id": 123,
        "username": "foo_bar"
    }
]

On the other hand if you decide that user_id is some internal system identifier for the user resource in your system (for example that could be the primary key in your SQL database) and you want to expose some friendlier unique id in your RESTful facade to the users, then you might consider using GET /users/{username}. Of course in this case you should very well define what a username is and what are the allowed characters for it because things could quickly turn into a nightmare if you allow some special characters in a username. Here's a good read on this topic that I very strongly encourage you to go through and very well understand what are the allowed characters in the path segment of an URL.

这篇关于在 REST API 中使用另一个资源的 id 命名获取资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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