-1

I can GET the data of a user on the /user/{username} URL and the reponse is

{
  "id" : 1,
  "username" : "testuser",
  "email" : "test@example.org"
}

In my implementation if you PUT data on the /user/{username} URL the backend creates or updates the user with the specified username.

What is the correct way to handle that case when the backend gets a username in the URL like /user/foo and in the http payload as well like:

{
  "id" : 1,
  "username" : "bar",
  "email" : "test@example.org"
}

Should I return 409 - Conflict or should I create or update a user with the username in the payload?

  • 1
    This question is a matter of opinion, so here's mine. You should not allow the same operation via two different actions. The way I would architect this is to implement PUT on /user for creating new users, and PATCH on /user/{username} for updates. No request should contain duplicate parameters, whether in the URL or HTTP payload. – bwest Mar 04 '19 at 20:31

1 Answers1

1

In original REST concepts, URL should effectively be URI - resource identifier, that said, UNIQUELY identify your user entity in the system.

Thus, if in your model username is unique and it is not possible to have 2 users with same name, then you can use username in resource identifier URL. Example - /user/foo

BUT, if it is possible that 2 users with different id can have same username, than according to strict REST you cannot use username as part of URL - it won't be REST anymore, just some web-service that accepts JSON in payload of PUT request.

Long story short:

1) If username is NOT unique identifier of user in your system - do NOT USE it in URL, use id instead, for example you've mentioned the URL will be /user/1

2) If username is UNIQUE identifier in your system - then you can have /user/foo.

============================================================================
In both cases you need to do integrity check that values in payload correspond to value in URL:
for 1) you check that id in URL is the same as in payload
for 2) you check that username in URL is the same as in payload

In case of inconsistency, I'd return status HTTP 422 Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors. Which exactly describes semantic inconsistency - structure of JSON payload is correct, but semantically id or username in URL and payload do not match.

Taras Slipets
  • 136
  • 1
  • 9