Including Id in URI for PUT requests

前端 未结 4 1543
庸人自扰
庸人自扰 2020-12-24 12:14

I was reading some documents about the appropriate use of URI\'s using rest services and I came across an example for basic GET .. DELETE requests.

The example uri\'

相关标签:
4条回答
  • 2020-12-24 12:41

    The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

    You want to PUT a resource to the same URI you intend to GET it from.

    RFC 72314.3.4 PUT

    0 讨论(0)
  • 2020-12-24 12:46

    PUT http://example.com/api/users + body behaves like the put of a map with the key http://example.com/api/users and the value the body. A new entry is created if none exists, else the existing one is overridden.

    Question: what is the resource behind http://example.com/api/users ?

    Answer: the same than the one provided by GET http://example.com/api/users, the list of all users.

    So, the command PUT http://example.com/api/users means that you replace the list of all users with the one you provide.

    For consistency, the body should contain an array of users:

    [
      {
        Id: 1,
        FirstName: 'John',
        LastName: 'Doe'
      },
      {
        Id: 2,
        FirstName: 'Albert',
        LastName: 'Einstein'
      }
    ]
    
    0 讨论(0)
  • 2020-12-24 12:50

    Another benefit for including id in URL for put request is CREATE/UPDATE function can share some logic.

    Let's say you have this user table with 3 colums.

    id(primary key, auto increment) | name | age
    

    Creating a user will generate a ID.

    POST /users
    {
      name: "foo"
      age: 25
    }
    -> generate id 123
    

    Because id is in URL, you can use the same request body structure for updating a user.

    PUT /users/123
    {
      name: "bar"
      age: 25
    }
    

    This might be not so related to REST principal, but it could simplify the code for request handling in practice depending on your languages/frameworks.

    0 讨论(0)
  • 2020-12-24 12:53

    I was going to ask a similar question, but I think I found the answer. I am not sure if it is by REST principles, but here is why it would be bad not to include ID in the URI. So say your PUT is like:

    PUT http://mydomain.org/api/users
    

    And then you happen to update multiple users with different id's but the same URI cause there is no ID in your URI. Then, an important thing to know here is that PUT is idempotent http verb. This means that calling it once should have the same effect as calling it mulitple times. Therefore, some intermediate node in the network, just following the fact that you PUT multiple times, might ignore all but one of your requests cause they have the same URI. Finally, that's definetely not what you want cause the intention was to update multiple users not only one.

    0 讨论(0)
提交回复
热议问题