Best Practices in Retrieving Related Data in a REST API

点点圈 提交于 2019-12-10 18:46:43

问题


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).

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/').

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/"
    }
]
}

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

I am using Django and django-tastypie

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/7460934/best-practices-in-retrieving-related-data-in-a-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!