gpt4 book ai didi

API访问多种资源的REST设计

转载 作者:行者123 更新时间:2023-12-02 00:12:23 26 4
gpt4 key购买 nike

想象一个为电视列表应用返回 JSON 数据的 API,例如 zap2it TV listings.

它基本上是一个电视 channel 列表,以及每个 channel 当前和以后正在播放的节目。目前,我有一个返回所有 channel GET/channels 的 API。但是,需要为该数据中的每个 channel 添加当前正在播放的节目。我正在考虑添加一个新的 API,GET/channels/on_now,以区别于当前的 API。 对于新 API,我想澄清这一点,我不想为每个 channel 单独调用,需要为所有 channel 返回当前显示的数据。 这是一个吗?良好的 REST API 设计?

当前 GET/channels JSON 数据

[
"channel": {
"channelName": "KRON4",
},
"channel": {
"channelName": "KTOV5",
},
...
]

新 API GET/channels/on_now 的预期 JSON 数据如下

[
{
"channel": {
"channelName": "KRON4",
},
"on_now": {
"startTime": "2012-06-04T11:30:00",
"endTime": "2012-06-04T12:00:00",
"shortDescription": "Latest local, statewide & national news events, along with sports & weather.",
"shortTitle": "4:30am Newscast"
}
},
{
"channel": {
"channelName": "KTOV5",
},
"on_now": {
"startTime": "2012-06-04T11:30:00",
"endTime": "2012-06-04T12:30:00",
"shortDescription": "Local morning news and weather report",
"shortTitle": "Morning Newscast"
}
},
...next channel...
]

最佳答案

我建议专注于内容,而不是网址。

示例:您有一个入口点“/”。这是 API 中的唯一 URL。获取它返回 st 就像

{
"channels" : {
"href" : "path.to/channels"
},
"programs" : {
"href" : "path.to/programs"
}
}

要检索 channel 列表,您可以获取相应的 URL(您之前不需要知道该 URL)并获取,例如:

[
{
"name" : "BBC",
"id" : 452,
"href" : "path.to/channels/452"
},
{
"name" : "FOO",
"id" : 112,
"href" : "path.to/channels/112"
}
]

有关 BBC 的详细信息,您可以通过提供的 URL 获取:

{
"name" : "BBC",
"id" : 452,
"self" : "path.to/channels/452",
"live_url" : "link.to.bbc.cast",
"whatever" : "bar",
"current" : "path.to/channels/452/current",
"program" : "path.to/channels/452/program"
}

等等。 URL 是动态发现的;您可以随时修改它们。 API 的核心在于内容:您必须就返回内容(字段、类型等)与客户达成一致。您最终调用上面的“当前”URL 来获取当前节目的信息。

阅读此处了解更多信息:http://kellabyte.com/2011/09/04/clarifying-rest/

OP评论后编辑:

您可以引入“embed”参数来限制请求数量:

GET path.to/channels/452?embed=current

将返回:

{
"name" : "BBC",
"id" : 452,
"self" : "path.to/channels/452",
"live_url" : "link.to.bbc.cast",
"whatever" : "bar",
"current" : {
"self" : "path.to/channels/452/current",
"name" : "Morning Show",
"start_time" : "(datetime here)",
"end_time" : "(datetime here)",
"next" : "whatever.comes.ne/xt"
},
"program" : "path.to/channels/452/program"
}

关于API访问多种资源的REST设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10888774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com