RESTful Many-to-Many possible?

前端 未结 3 1975
天命终不由人
天命终不由人 2020-12-28 09:19

How to I represent a complex resource for a REST post?

Hello, Currently I have an application which when the user hits \"save\" it iterates over all of the form el

3条回答
  •  眼角桃花
    2020-12-28 09:35

    The approach I would use here is hypermedia and links:

    /property
    /property/{id}
    /property/{id}/features/{id}
    

    Depending on your domain you might even get away with:

    /property/{id}/features/{name}
    

    or

    /property/{id}/features/byname/{name}
    

    Thus you can do REST operations and serve JSON or XHTML hypermedia.

    Property details:

    Request: GET /property/1
    Response:
    {
      ..
      "name": "Brentwood",
      "features": "/property/1/features"
      ..
    }
    

    Brentwood's features:

    GET /property/1/features
    {
      ..
      "Kitchen": "/property/1/features/1",
      "Dog Room": "/property/1/features/dog%20room",
      ..
    }
    
    GET /property/1/features/1
    {
      ..
      "Induction hob": "/property/1/features/1/1",
      "900W microwave": "/property/1/features/1/23",
      "nav-next" : "/property/1/features/dog%20room",
      ..
    }
    

    To add a relation you can do something like this:

    POST /property/1/features
    {
      ..
      "Name": "Oven Hob"
      ..
    }
    

    If you know what the relation will be you use a PUT:

    PUT /property/1/features/23
    {
      ..
      "Name": "Oven Hob"
      ..
    }
    

    You can serve multiple media types:

    GET http://host/property/1/features/dog%20room.json
    
    GET http://host/property/1/features/dog%20room.xhtml
    

    For the response in xhtml the response can use named links like this:

    ..
     
    ..
    

    There are other aspects of REST that you can use such as response code which I did not include above.

    Thus, to model relations you make use of links which can be in itself a resource that can be operated on with GET, PUT, POST and DELETE or even custom verbs such as ASSOCIATE or LINK. But the first four are the ones that people are used to. Remember PUT is idempotent but not POST. See PUT vs POST in REST

    Edit: You can group your links into JSON arrays to give structure to your hypermedia.

提交回复
热议问题