带有类别的REST API设计

时间:2018-07-27 07:20:58

标签: rest api-design

比方说,有一个移动应用程序可以接收各种类型的通知(如WhatsApp通知,Facebook Messenger通知等)。为此,哪种REST API结构更好?

/users/test@abc.com/notifications //Gives all the notifications

以下两种格式之间的混淆。

/users/test@abc.com/notifications?category=whatsapp,facebook    //Gives all the notifications

/users/test@abc.com/notifications/whatsapp  //Gives only whatsapp notification
/users/test@abc.com/notifications/facebook  //Gives only facebook notification

访问单个通知资源

/users/test@abc.com/notifications/facebook/{notification-id}

/users/test@abc.com/notifications/{notification-id}

2 个答案:

答案 0 :(得分:1)

如果资源具有唯一ID,则应该可以直接访问该资源,因此我认为

/notifications/{id}

最有意义。在过滤方面,这可能更多是关于偏好的事情。我认为这是最惯用的方法

/notifications    // fetch all notifications
/notifications/facebook    // fetch all Facebook messages
/notifications/whatsapp    // fetch all WhatsApp messages
/users/{id}/notifications    // fetch user notifications 
/users/{id}/notifications/facebook    // fetch user Facebook notifications 
/users/{id}/notifications/whatsapp    // fetch user WhatsApp messages

答案 1 :(得分:1)

这实际上取决于您如何定义grouping资源以及其notification类型(categorywhatsapp ...)的关系。

facebook依赖

如果通知的结构不依赖于其类别,则您要在没有任何类别上下文的情况下访问它:

category

您可以将类别用作通知集合的过滤器:

/users/test@abc.com/notifications/{notification-id}

/users/test@abc.com/notifications?category=whatsapp,facebook 依赖

否则,如果通知在结构上取决于其类别(例如,如果您想在处理category通知时定义与在处理{{1} }通知),那么您可能要根据其类别来区分通知:

whatsapp

在这种情况下,您可能会:

facebook

定义了2个不同的通知(尽管它使用相同的标识符)。

现在请求收集此类通知与以前的“非类别相关”情况有些不同。

如果您只想收到/users/test@abc.com/notifications/whatsapp/{whatsapp-notification-id} /users/test@abc.com/notifications/facebook/{facebook-notification-id} 通知,则只需调用类别资源即可:

/users/test@abc.com/notifications/whatsapp/1
/users/test@abc.com/notifications/facebook/1

但是,如果要搜索不同的类别,则无法将请求应用于特定的类别资源。确实,在处理whatsapp条通知时,要求/users/test@abc.com/notifications/whatsapp 条通知是没有意义的:

facebook

一种解决方案是发出与类别数量一样多的请求:

whatsapp

但是您以后必须合并结果。

另一种解决方案是直接从

应用查询
/users/test@abc.com/notifications/whatsapp?category=facebook # weird

但是结果将不同于“非类别相关”情况。实际上,您将无法直接拥有通知列表,但可以拥有访问通知列表的类别列表。