RESTful API - 如何为同一资源返回不同的结果? [英] RESTful API - How do I return different results for the same resource?

查看:49
本文介绍了RESTful API - 如何为同一资源返回不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为同一资源返回不同的结果?

How do I return different results for the same resource?

我一直在寻找构建 RESTful API 的正确方法.那里有大量的重要信息.现在我实际上正在尝试将其应用到我的网站并遇到了一些障碍.我发现了一些建议,说将资源基于您的数据库作为起点,考虑到您的数据库应该结构合理.这是我的场景:

I have been searching for some time now about the proper way to build a RESTful API. Tons of great information out there. Now I am actually trying to apply this to my website and have run into a few snags. I found a few suggestions that said to base the resources on your database as a starting point, considering your database should be structured decently. Here is my scenario:

这里有一些关于我的网站和 API 用途的信息

Here is a little information about my website and the purpose of the API

我们正在创建一个允许人们玩游戏的网站.该 API 应该允许其他开发人员构建自己的游戏并使用我们的后端来收集用户信息并进行存储.

We are creating a site that allows people to play games. The API is supposed to allow other developers to build their own games and use our backend to collect user information and store it.

我们有一个存储所有玩家数据的players 数据库.开发者需要根据 user_id(拥有玩家数据的人)或 game_id(收集数据的游戏)来选择这些数据.

We have a players database that stores all player data. A developer needs to select this data based on either a user_id (person who owns the player data) or a game_id (the game that collected the data).

资源

http://site.com/api/players

问题:

如果开发人员使用 GET 调用我的资源,他们将收到玩家列表.由于有多个开发者使用这个系统,他们必须指定一些 ID 来选择所有玩家.这是我发现问题的地方.我希望开发人员能够指定两种 ID.他们可以通过 user_id 或 game_id 选择所有玩家.

If the developer calls my resource using GET they will receive a list of players. Since there are multiple developers using this system they must specify some ID by which to select all the players. This is where I find a problem. I want the developer to be able to specify two kinds of ID's. They can select all players by user_id or by game_id.

  1. 你是如何处理这个问题的?
  2. 我需要两个单独的资源吗?

推荐答案

假设您有一个控制器名称玩家",那么您将有 2 个方法:

Lets say you have a controller name 'Players', then you'll have 2 methods:

function user_get(){
   //get id from request and do something
}

function game_get(){
//get id from request and do something
}

现在网址将如下所示:http://site.com/api/players/user/333http://site.com/api/players/game/333

now the url will look like: http://site.com/api/players/user/333, http://site.com/api/players/game/333

  1. 玩家是控制器.
  2. 用户/游戏就是行动

如果您使用 phil sturgeon 的框架,您会这样做,但网址将如下所示:http://site.com/api/players/user/id/333, http://site.com/api/players/game/id/333

If you use phil sturgeon's framework, you'll do that but the url will look like: http://site.com/api/players/user/id/333, http://site.com/api/players/game/id/333

然后你使用:$this->get('id');

这篇关于RESTful API - 如何为同一资源返回不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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