HATEOAS POST link 在 HAL 中

HATEOAS POST link in HAL

如何在 HAL 中描述 POST links?

我正在设计一个带有 HATEOAS 约束的 RESTful API,类似于 Wikipedia's HATEOAS example 但用 HAL JSON 表示(删除方案、主机等)清晰度):

GET /accounts/12345

{
  "id" : 12345,
  "balance" : 100.00
  "_links" : {
    "self" : {
      "href" : "/accounts/12345"
    },
    "transfer" : {
      "href" : "/accounts/12345/transfer{?amount,target}",
      "templated" : true
    }
  }
}

要执行“传输”操作,客户端大概会做:

GET /accounts/12345/transfer?amount=100.00,target=54321

{
  "id" : 34567,
  "amount" : 100.00
  "_links" : {
    "self" : {
      "href" : "/transfers/34567"
    },
    "source" : {
      "href" : "/account/12345"
    },
    "target" : {
      "href" : "/account/54321"
    }
  }
}

通过 GET 调用“传输”link 在“传输”中创建一个新资源。但是使用 GET 来创建新资源并不是幂等的,而且“感觉”不对; RESTful 以资源为中心 API 会 POST:

POST {amount: 10.00, source: 12345, target: 54321}  /transfers/

{
  "id" : 34567,
  "amount" : 100.00
  "_links" : {
    "self" : {
      "href" : "/transfers/34567"
    },
    "source" : {
      "href" : "/account/12345"
    },
    "target" : {
      "href" : "/account/54321"
    }
  }
}

但是我如何在 HAL 中描述此 POST 和所需的表单元素,以便客户端可以在不进行硬编码的情况下只做“正确的事情”?也许是这样的:

{
  "id" : 12345,
  "balance" : 100.00
  "_links" : {
    "self" : {
      "href" : "/accounts/12345"
    },
    "transfer" : {
      "href" : "/transfers{?amount,source,target}",
      "templated" : true,
      "method" : "POST"
    }
  }
}

但是 method 不是 HAL specification 的一部分,也没有类似的标识符——所以感觉我走错了路...

也许我的客户应该只“知道”transfer returns 匹配传输资源的 GET,以及 POST 到 transfer 的 GET 创建新的传输资源。

FWIW,我的实现使用 Spring Boot 2 和 Spring HATEOAS,所以后续问题是如何用 Spring HATEOAS 表达这个...

你不能用 HAL 做到这一点。 Mike Kelly,HAL 的创造者,states on GitHub

The "HAL way" of doing this is to use the link rel documentation to convey the available methods in a human readable form. ie. your barks example would look like this (notice the "barks" link rel is now a URL)

{
   "_links": {
        "http://docs.example.com/barks": { "href": "/v1/dogs/1/barks" }
    }
}

and if a developer fetches the URL http://docs.example.com/barks in a browser, the documentation can specify the available methods, valid request bodies, potential response codes, response bodies, etc. The developer will then codify this into the client she is building.

恕我直言,这是 HAL 规范的一个主要缺陷,但还有其他媒体类型可以解决此问题,例如 Mason or the HAL extension HAL-FORMS。可能值得检查这些,尽管我不确定它们如何与 Spring.

集成