3.3.3.Implementing REST API CRUD operations
Uniform Interface Constraint has 3 parts:
1.HTTP method, HTTP協議語句 (Protocol statement)
2.HTTP status code
3.Representation formats
HTTP method
HTTP Verbs/ Methods = CRUD
HTTP status code
All HTTP responses have a 3 digit status code
1xx: Informal e.g., 100: Continue
2xx: Success e.g., 200: OK
3xx: Redirection e.g., 307: Temporary redirect
4xx: Client error e.g., 404: Not found
5xx: Server error e.g., 500: Internal server error
[POST]
基於給定的訊息, 在當前資源的下一層創建新的資源
e.g., /vacations, /vacations/{id}/reviews
不符合冪等性
類型1: POST-to-append
在當前資源的下一層創建新的資源
類型2: overloaded POST
"向數據處理流程提供例如表單提交結果的數據塊"
不僅被用作創建新的資源, 也被用於傳輸任何形式的變化, 他將PUT, DELETE, PATCH, LINK, UNLINK所有的方法混合成一個方法
Response
狀態碼
Sucesss: e.g., code = 201
May return a link (id) to new resource in Location header e.g., Location: http://api/acme.com/vacations/121/reviews/2
May return a new object
Failure:
4xx Bad request e.g., 400 missing required field
5xx Issue in processing e.g., 503 database unreachable
響應表頭 (response header)
content type
Content-Type
application/vnd.collection+json
[GET]
從資源處獲取一個表述(representation), 並且沒有主觀去改變資源的意圖, 但在現實生活中不能保重GET請求是安全的, 在設計時賦予GET請求重大的副作用是不合理的
e.g., /vacations, /vacations/{id}
Response
實體消息體 (entity body)
狀態碼
Sucesss: e.g., code = 200 OK
Send back the response requested format e.g., GET http://api/acme.com/vacations/121
Failure:
4xx Bad request e.g., 404 Resource not found
5xx Issue in processing e.g., 500 Internal server error
響應表頭 (response header)
content type
[PUT/PATCH]
用於修改資源狀態的請求
PUT
Update all attributes of existing resource - effectively replace
Can also CREATE if client provide ID (not suggested)
PATCH
Modified parts of an existing resource.
符合冪等性 (Idempotence)
Return
Sucesss: e.g., code = 200 OK, 204 Content, 201 Created
Resource in body of response(optional)
No need to send the link (optional)
[DELETE]
銷毀一個資源
e.g., /vacations, /vacations/{id}
符合冪等性 (Idempotence)
發送兩次請求和發送一次請求的響應是一樣的
Response
實體消息體 (entity body)
狀態碼
Sucesss:
code = 200 OK
May return deleted resource in the response body
code = 204
No returned content = 204
Failure:
4xx Bad request e.g., 404 Resource not found
5xx Issue in processing e.g., 503 database unreachable
[OPTIONS]
獲取這個資源所能響應的HTTP方法列表
[LINK]
[UNLINK]
Resource representation
Request
Query parameters
e.g., /search?q=iphone&format=xml
HTTP Header accepts
e.g., Accepts: application/json
Resource Format Suffix
e.g., /programmes/schedules/fm/today.json
Use of HTTP Accept header is not so common
Most providers set default format = json
Response
1.Content-Type
2.HTTP status code = 415, Requested format not supported
3.Document
(a) supported formats
(b) how requester specifies
Last updated