1. 前言
這項技術是由originally drafted by Yehuda Katz in May of 2013 提出的。一個概念或技術的出現往往都有它的目的與精神,整理如下
Its original goal was to create a communication model based around defined interactions,rather than leaning on per-application “ad-hoc” code
ad-hoc
:「特設的、特定目的的、即席的、臨時的、將就的、專案的」
- 官網
JSON:API is a specification for how a client should request that resources be fetched or modified, and how a server should respond to those requests.
JSON:API is designed to minimize both the number of requests and the amount of data transmitted between clients and servers. This efficiency is achieved without compromising readability, flexibility, or discoverability.
- will 保哥
JSON 幾乎成為 Web 業界的標準傳輸格式,不過由於 JSON 的格式非常彈性,不少人光是為了爭辯 JSON 到底該長得怎樣而吵半天,我也好幾次被客戶「自訂」的 JSON 格式打敗,不但缺發一致性,更有前後版本相容性的問題,身為前端攻城獅的你能不在乎嗎?!
現在有了 JSON API 這份標準規格,可以幫助你**增加效率 (減少溝通)**、套用工具支援 (或現有函式庫)、並且讓你專注在你的應用程式開發上,不再為了 JSON 的長相而煩惱!
目前實作 JSON API 的函式庫很多了,有支援 ASP.NET WebAPI, Json.NET, 與 Entity Framework 的 JSONAPI . NET,其他還有 PHP, node.js, Ruby, Python, Go 都有相對應的 Server/Client 實作出現,使用上非常方便!
自己的結語
JSON APIs 的資料結構 很像是RMDBS 與SQL 的另一種形式呈現。
2. Client & Server Responsibilities
在client 跟server 都有一些職責在,大家都必須在 header 中聲明application/vnd.api+json
而JSON API 已經在IANA
機構完成註冊囉,它的MIME 類型就是application/vnd.api+json
3. Document Structure
3.1. Top Level
MUST
- data
- errors
- meta
MAY
- jsonapi
- links
- included
Primary data MUST be either:
- single resource object,resource identifier object, or null
- an array of resource objects
Primary data MUST have type and id
可以想像成是資料表與資料的ID
3.2. Resource Objects
3.2.1. Identification
每一個RO(Resource Objects) 都必須要有id,type,且必須是字串
3.2.2. Fields
attributes ,relationships 在這邊統稱fields
3.2.3. Attributes
表達資料的資訊,可以想像是我們在資料表欄位
3.2.4. Relationships
MUST contain at least one
links
self
1
2
3
4
5
6
7
8
9"relationships": {
"author": {
"links": {
"self": "http://example.com/articles/1/relationships/author",
"related": "http://example.com/articles/1/author"
},
"data": { "type": "people", "id": "9" }
}
}relationships 下的 links->self 可以想像是依據文章編號1的作者,再反推找到所有文章?
related
1
2
3
4
5
6
7
8
9"relationships": {
"author": {
"links": {
"self": "http://example.com/articles/1/relationships/author",
"related": "http://example.com/articles/1/author"
},
"data": { "type": "people", "id": "9" }
}
}取得文章編號1的作者資訊?
data
此關聯資源的資料,一樣必須包含type,id
meta
3.3. Related Resource Links
3.4. Resource Linkage
3.5. JSON:API Object
1 | { |
3.6. Compound Documents
To reduce the number of HTTP requests, servers MAY allow responses that include related resources along with the requested primary resources. Such responses are called “compound documents.
試著解釋以下文檔
1 | { |
4. 參考資料
- JSON APIs en
- JSON APIs cn
- 聊聊 Spring HATEOAS
- 你的REST不是REST?
- 重新認識HTTP請求方法
- soap-vs-rest-vs-json
- Headless CMS: REST vs JSON:API vs GraphQL
- How Does JSON:API Compare To REST and GraphQL?
- SOAP vs REST vs JSON - a 2020 comparison
- REST 與JSON API 比較
- JSON API Server
- JSON API Client
- JsonApiDotNetCore
- JSONAPI 與 REST