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

时间:2012-07-26 14:11:42

标签: api codeigniter rest

问题

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

详细

我一直在寻找构建RESTful API的正确方法。那里有很多很棒的信息。现在我实际上正在尝试将此应用到我的网站,并遇到了一些障碍。我发现了一些建议,说基于数据库的资源是一个起点,考虑到你的数据库应该结构合理。这是我的情景:

我的网站:

以下是有关我的网站和API目的的一些信息

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

场景1:

我们有一个players数据库,用于存储所有玩家数据。开发人员需要根据user_id(拥有播放器数据的人)或game_id(收集数据的游戏)选择此数据。

资源

http://site.com/api/players

问题:

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

  1. 你怎么处理这个?
  2. 我需要两个独立的资源吗?

3 个答案:

答案 0 :(得分:2)

假设你有一个控制器名称'玩家',那么你将有两种方法:

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

  1. 播放器是控制器。
  2. 用户/游戏是行动
  3. 如果您使用phil sturgeon的框架,您会这样做,但网址将如下所示: http://site.com/api/players/user/id/333http://site.com/api/players/game/id/333

    然后您使用以下内容获取ID:$this->get('id');

答案 1 :(得分:0)

您可以通过指定查询字符串参数来限制结果,即:

http://site.com/api/players?id=123

http://site.com/api/players?name=Paolo

答案 2 :(得分:0)

使用phil的REST服务器库: https://github.com/philsturgeon/codeigniter-restserver

我在产品环境中使用oauth和api密钥生成来使用此库。您将创建一个api控制器,并为您想要的每个请求定义方法。在我的情况下,我创建了一个完全独立的codeigniter实例,并根据我的需要编写了我的模型。

你也可以使用这个REST库来插入数据,这一切都在他的文档中。

这是一段视频,菲尔在2011年的基础知识上进行了总结...... http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter

应该注意,RESTful URL意味着使用复数/单数措辞,例如;玩家=单数,玩家=全部或多于一个,游戏|游戏等。


这将允许您在控制器中执行此类操作

//users method_get is the http req type.. you could use post, or put as well.
public function players_get(){
  //query db for players, pass back data
}

您的API请求网址如下:

http://api.example.com/players/format/[csv|json|xml|html|php]

这将根据您模型中的查询返回所有用户的json对象。

或者

public function player_get($id = false, $game = false){
  //if $game_id isset, search by game_id
  //query db for a specific player, pass back data
}

您的API请求网址如下:

http://api.example.com/player/game/1/format/[csv|json|xml|html|php]

或者

public function playerGames_get($id){
  //query db for a specific players games based on $userid
}

您的API请求网址如下:

http://api.example.com/playerGames/1/format/[csv|json|xml|html|php]
相关问题