4

In a RESTful API I have user resources on /users and /users/:id with their usernames, email-addresses and passwords.

When I want to update a users information I can easily do a PATCH:/users/:id with some JSONPatch data.

The problem now is that I can't figure out how to handle a change password scenario with a currentPassword, newPassword and newPasswordConfirm form.

What METHOD should be used (PATCH seems appropriate but problematic) and in what way should the data be transmitted (body/header/...).

In a wider scope - how should a patch with further fields for validation be handled.

This post seems related but doesn't cover this exact topic.

Community
  • 1
  • 1
Aides
  • 3,643
  • 5
  • 23
  • 39

2 Answers2

10

Instead of PATCH, to partially update a user resource, have you ever considered PUT to replace the password?

Your endpoint could be /users/:id/password, where password is a sub resource of the user resource. And your request to replace the password would be like:

PUT /users/1/password HTTP/1.1
Host: api.example.com
Content-Length: 113
Content-Type: application/json
Authorization: Basic YWRtaW46c2VjcmV0

{
    "currentPassword" : "secret",
    "newPassword": "othersecret",
    "newPasswordConfirm" : "othersecret"
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 4
    I did consider this solution but wanted to avoid exposing the individual fields on the API. Apart from that I would rather use the `POST` method, since the `PUT` operation is defined to be idempotent while this operation would not clearly be. – Aides Apr 18 '16 at 11:59
  • Would you mind looking at my answer and providing feedback? – Aides Apr 18 '16 at 12:00
1

After some deeper dive into JSONPatch I was able to come up with the approach of adding test operations to the patch data.

This could look somewhat like:

[
    { "op": "test", "path": "/password", "value": "oldPassword" },
    { "op": "replace", "path": "/password", "value": "newPassword" },
    { "op": "test", "path": "/password", "value": "newPasswordConfirm" }
]

Are there any concerns using this method?

Community
  • 1
  • 1
Aides
  • 3,643
  • 5
  • 23
  • 39
  • I think this approach will work fine. However, IMHO, the `PUT` approach makes it clearer. – cassiomolin Apr 18 '16 at 12:02
  • Okay, one thing that might be a dealbreaker is the fact that I would have to assure that the consumer does actually use this request format. Without further server-side validation a consumer could just send the replace without the test cases. – Aides Apr 18 '16 at 12:17