API notes

APIs, protocols

Eddie Cheng
6 min readJun 23, 2022

REST : 以資源為導向的風格

RPC: 以方法為導向的風格

SOAP:

GraphQL:

gRPC:

JSON-RPC (blockchain):

Terms

  • Resource: The target of an HTTP request. It can be a document, a photo, or anything else
  • Identifier: I think is equal to URI and two common forms are URL and URN

e.g

urn:isbn:9780141036144

  • Serialization: A Object becomes a string (JSON, yml, …)

Status Code

  • Status 204 代表的是「請求成功,但沒有 BODY」, 這個比較常用在 DELETE 操作
  • Status 207

Authorization Rules

Each API should have it own rule

E.g.

  • Create account API: A logged-in user can only create an account for him/herself
  • Get account API: A logged-in user can only get the account he/she owns
  • List account API: A logged-in user can only list theaccounts he/she owns
  • Transfer Money API: A logged-in user can only send money from his/her own account

GraphQL

VS Restful API

  • A connection can take all needed data (page-oriented?)
  • Fetch data depending on a field => instead of whole user, backend can return user.profile
  • Real-time API document

Some client does not support GraphQL => use RestFul API, eg IoT

RESTful API

  • Resources should be nouns e.g. ticket, user, customer
  • For JS, always use camelCase for field name
  • Pretty print by default and ensure gzip is supported

Naming

  • Endpoint: always use a plural
/tickets
/tickets/12

Dealing with relations

If a relation can only exist within another resource

GET /tickets/12/messages/5
POST /tickets/12/messages // Creates a new message #5 for ticket #12
PUT /tickets/12/messages // Updates message #5 for ticket #12
PATCH /tickets/12/messages // Partially updates message #5 for ticket #12

Alternative 1: If a relation can exist independently of the resource => create its own API

Alternative 2: https://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#autoloading

Versioning

Pagination

Some Scenarios

[GET] /users 
[GET] /users/<USERNAME>

上述沒有資料的情形會有兩種:

  • 在 users 中沒有任何 user => status 200 並返回 []於 body
  • 名稱為 <USERNAME> 的 user 不存在 => status 404 視情況返回 body

gRPC

  • gRPC is free and open-source framework developed by Google. Initial release version in 2016
  • gRPC is part of Cloud Native Computation Foundation (CNCF) => 有人管

Motivations

  • Server and server need extra APIs to communicate => lots of scenarios to consider: protocol, authentication, payload format, error handling
  • Need Efficient (gRPC better than REST(?))
  • Need Simple => no need to handle libraries

Great improvement of gRPC

Protocol Buffers:

  • Fast: Binary transport faster than JSON
  • type-safe
  • a single source of truth: all languages have a same spec
  • Generators for different languages
  • streaming feature (connection is always open)
Messages (data request and response)message Runner {
string uuid = 1;
optional string os =2;
string token = 4;
}
Service

--

--

Eddie Cheng

「0」が過去で「1」が未来「今」は何処にもない