Skip to content

Restful API tips

restful api 设计的相关原则

设计的相关5个动作

  • GET

  • PUT

  • DELETE

  • POST

  • PATCH

Custom Methods

Design Custom Methods

custom methods的http设计:

https://service.name/v1/some/resource/name:customVerb

采用:代替/的理由在于,可以支持任意的路径

关于custom methods部分,遵循下面几个原则

  • 应尽量使用POST方法,因为其支持灵活的语义

  • 即使要使用其他动作的话,也需尽量符合其对应的语义学

  • GET方法,需要保持独立以及幂等

  • 关于body的一些建议

代码部分的示例:

// This is a service level custom method.
rpc Watch(WatchRequest) returns (WatchResponse) {
  // Custom method maps to HTTP POST. All request parameters go into body.
  option (google.api.http) = {
    post: "/v1:watch"
    body: "*"
  };
}

// This is a collection level custom method.
rpc ClearEvents(ClearEventsRequest) returns (ClearEventsResponse) {
  option (google.api.http) = {
    post: "/v3/events:clear"
    body: "*"
  };
}

// This is a resource level custom method.
rpc CancelEvent(CancelEventRequest) returns (CancelEventResponse) {
  option (google.api.http) = {
    post: "/v3/{name=events/*}:cancel"
    body: "*"
  };
}

// This is a batch get custom method.
rpc BatchGetEvents(BatchGetEventsRequest) returns (BatchGetEventsResponse) {
  // The batch get method maps to HTTP GET verb.
  option (google.api.http) = {
    get: "/v3/events:batchGet"
  };
}