HATEOAS - How to model link relations that change state

前端 未结 4 795
眼角桃花
眼角桃花 2021-01-05 00:59

Following HATEOAS principles that each states should be hyperlinked, what is the best way to model links that change resource state?

Let\'s take classical example wi

4条回答
  •  死守一世寂寞
    2021-01-05 01:53

    I would suggest either of these two models. The first is the classic one, but with rel="edit-form" and using PATCH where available. The second is an alternative which comes about through some lateral thinking about how the HTTP resource model maps onto your application domain model (namely, that the two don't have to have a 1:1 mapping).


    Solution 1

    Edit the resource in-place.

    HTML compatible:

    HTTP/1.1 200 OK
    Content-Type: text/html
    Location: /orders/1/
    
    ...Edit...
    

     

    HTTP/1.1 200 OK
    Content-Type: text/html
    Location: /orders/1/edit
    
    ...
    
    ...

     

    POST /orders/1 HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    _METHOD=PATCH&status=cancelled
    

    Rich client (e.g. HTML+Javascript) compatible:

    PATCH /orders/1 HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    status=cancelled
    

    and/or

    PATCH /orders/1 HTTP/1.1
    Content-Type: text/json
    
    {
        "status": "cancelled"
    }
    

    the _METHOD key is a well-known means of providing REST frameworks with the correct method due to HTML's lack of support for HTTP.


    Solution 2

    Or, Delete the resource (and, incidentally, create a new one)

    DELETE /orders/1 HTTP/1.1
    

     

    HTTP/1.1 201 Created
    Location: /cancelled-orders/1
    

    For more info on this way of mapping web resources to domain objects, please see my answer to a similar question.

    Another answer you may wish to read is this one.

提交回复
热议问题