在REST API中检索相关数据的最佳做法 [英] Best Practices in Retrieving Related Data in a REST API

查看:141
本文介绍了在REST API中检索相关数据的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个REST API,其中我有一个资源链接到其他资源(相关模型,在编程观点)。

So I have a REST API in which I Have a resource in which other resources are linked to (related models, in programming point of view).

所以我现在正在做的是,每当我请求一个资源时,相关资源都会通过URL引用('/related_data/related_data_id/').

So how I am doing it right now is that whenever I request for a resource, related resources are referenced via URLs ('/related_data/related_data_id/').

但是,我担心,我有5个相关资源被提取,我将执行5个GET请求。我正在写一个iPhone客户端,我想知道如果这是如何正确地使用REST(我正在返回URL)。一个示例的JSON响应是这样的:

However, I worry that, let's say there are 5 related resources to the one I'm retrieving, is that I would perform 5 GET requests. I am writing an iPhone client and I'm wondering if this is how to properly do it using REST (that I'm returning URLs). A sample JSON response is this:

{
"meta": {
            "limit": 20, 
            "next": null, 
            "offset": 0, 
            "previous": null, 
            "total_count": 2
        }, 
"objects": [
    {
        "away_team": "/api/team/3/", 
        "country": "/api/country/1/", 
        "event_date": "2011-08-16", 
        "event_time": "06:00:00", 
        "event_timezone": "GMT", 
        "home_team": "/api/team/4/", 
        "id": "1", 
        "level": "/api/level/4/", 
        "resource_uri": "/api/event/1/", 
        "tournament": "/api/tournament/1/"
    }, 
    {
        "away_team": "/api/team/4/", 
        "country": "/api/country/1/", 
        "event_date": "2011-09-29", 
        "event_time": "12:00:00", 
        "event_timezone": "UTC", 
        "home_team": "/api/team/3/", 
        "id": "2", 
        "level": "/api/level/1/", 
        "resource_uri": "/api/event/2/", 
        "tournament": "/api/tournament/6/"
    }
]
}

这是一个适当的方式在REST中考虑每个URI必须映射到资源和所有这些东西?

Is this a proper way of doing it in REST, considering that "each URI must map to a resource" and all those things?

我正在使用Django和django-tastypie

I am using Django and django-tastypie

提前感谢!

推荐答案

是的;如果相关资源独立更新,则是适当的。 REST架构取决于缓存的性能,因此最适合用作原子实体的资源(请参阅更多在这里)。这样,您可以更新资源B并使其代表性更新,而无需更新资源A.参见这个SO评论了解更多设计细节。

Yes; that is proper if the related resources are updated independently. REST architectures depend on caching for performance, and therefore work best with resources which act as atomic entities (see more here). That way, you can update resource B and have its representation be fresh without having to update resource A. See this SO comment for more design details.

这篇关于在REST API中检索相关数据的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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