2. How to safely support these actions on resources in a web
API while maintaining a simple, predictable, and functional
API using what we’ll call custom methods.
2
4. 9.1 Motivation
1. when we need the ability to express a specific action that doesn’t really fit
very well in one of the standard methods (ch7).
2. how to integrate to current systems or framework:
○ should we try to jam the behavior we want into the existing methods, bending the framework a
bit to fit our needs? Or
○ should we change our behavior into a form that fits a bit more cleanly within the framework?
Or
○ should we change the framework to accommodate our new scenario?
4
7. 1. most state changes are transitions of some sort or another, and as a result,
transitioning to a new state is fundamentally different from setting the value of
a scalar field.
a. This field feels like it should be managed by the API service itself rather than updated by the
client.
b. 狀態 (State) 的改變 (transition) 應該由 Service 管理,不是 POST 過來
2. As we learned in chapter 7, standard methods really should NOT do anything
besides the specific action their name implies.
7
8. 9.2 Overview
Custom methods are nothing
more than API calls that fall
outside the scope of a standard
method.
8
9. 9.3 Implementation
1. 不要使用 farword slash (/) 作動詞區隔,像是 POST /rockets/1234567/launch (這很重
要)
a. Rick: 哪裡重要?
2. RPC 遵循規則: 動詞 + 名詞,像是 LaunchRocket or ArchiveDocument,避免使用 With / For 等
介系詞。
9
15. 匯出單一 User 的所有 Email (General Users),
or
一個操作執行多個資源操作:
ex: 使用一個 API 匯出一堆 Email (Admin)
以下都是匯出多個資源。。。
1) POST /users/1:exportEmails
2) POST /users/1/emails:export
3) POST /users/1:export
哪個好?
更多參
閱
Ch23
15
19. 9.4 Trade-offs
the very existence of these custom methods tends to present a contradiction (矛
盾) with REST and the principles underpinning RESTful API design.
19
20. Summary
1. Custom methods should almost always use the HTTP POST method and never use the
PATCH method. They might use the GET method if the custom method is idempotent and
safe.
2. Custom methods use a colon (:) character to separate the resource target from the action
being performed (e.g., /missiles/1234:launch).
3. While side effects are forbidden for standard methods, they are permitted for custom
methods. They should be used sparingly and documented thoroughly to avoid confusion for
users.
4. In general, custom methods should target a collection when multiple resources from a
single collection are involved.
5. Sometimes, particularly for computational work, APIs might choose to rely on stateless
custom methods to perform the bulk of the work. This strategy should be used cautiously as
it’s easy for statefulness to eventually become important and can be difficult to introduce
later on.
20