首页 > 解决方案 > RESTful 设计 - 子资源端点

问题描述

我正在设计一个与发票一起使用的 REST API,并且每张发票都有状态历史记录。

有一个端点可以获取发票的状态历史记录,如下所示

/invoices/{invoice_id}/states

将其作为等价物包含在内是 RESTful 吗?是否推荐/需要?

/states/{invoice_id}

标签: restapi

解决方案


/invoices/{invoice_id}/states
/states/{invoice_id}

就 REST 而言,两个不同的标识符意味着两个不同的资源。这并不意味着服务器不能拥有两个具有同步表示的资源,但它确实意味着通用组件不会知道这两个资源“真的”是同一件事。

当您处理缓存失效时,这可能很重要。

例如:

# Assume: empty cache

onRead(/invoices/{invoice_id}/states)
    # Not available locally therefore
    GET /invoices/{invoice_id}/states
    200 OK
    # Representation from server is loaded into the cache
    # Representation from server is returned to caller

onRead(/states/{invoice_id})
    # Not available locally therefore
    GET /states/{invoice_id}
    200 OK
    # Representation from server is loaded into the cache
    # Representation from server is returned to caller

onRead(/invoices/{invoice_id}/states)
    # valid representation available locally therefore
    # Representation from cache is returned to caller

onRead(/states/{invoice_id})
    # valid representation available locally therefore
    # Representation from cache is returned to caller

onChange(/invoices/{invoice_id}/states)
    # PUT, PATCH, DELETE would all be similar
    POST /states/{invoice_id}
    200 OK
    # successful request, so cached copy is invalidated

onRead(/invoices/{invoice_id}/states)
    # Not available locally therefore
    GET /invoices/{invoice_id}/states
    200 OK
    # Representation from server is loaded into the cache
    # Representation from server is returned to caller

onRead(/states/{invoice_id})
    # valid representation available locally therefore
    # Representation from cache is returned to caller

所以最后,/states/{invoice_id}是在更改之前有一个副本,但在/invoices/{invoice_id}/states更改之后会有一个副本。

如果这有用,那就太好了!

但我的猜测是,它通常会产生不必要地难以追踪的问题。我更喜欢使用相同标识符访问同一文档的所有副本的设计指南,除非有可证明的商业价值。


推荐阅读