0

I'm new to designing RESTful APIs and currently developing APIs to manage students in a school.

Each student has a unique roll number that clients provide while adding/creating a user. Service creates an internal id that is unique for every user that is added.

If clients make multiple POST calls for the same user, what are the recommended options in this scenario? Success with an existing resource id? or an error? or something else.

l'-'l
  • 428
  • 1
  • 7
  • 18

2 Answers2

0

You have two options, POST and PUT, you can choose one of these or both based on your requirement.

If you choose POST, and if the resource already exists, throw an error saying the resource exists.

If you choose PUT, and if the resource already exists, then update the resource and return the existing resource id.

These are widely followed conventions which are intuitive for the api consumers. If you are deviating from these for any special cases then you have to make sure that the api consumers are aware of your convention.

This link might be super useful - PUT vs. POST in REST

Yuvaraj G
  • 1,157
  • 9
  • 17
  • Thanks. POST with error seems logical to me as well. With PUT - do not want to lose the properties that may be updated post original resource creation, as with PUT I'll have to replace it (idempotent). – l'-'l Dec 08 '19 at 16:19
0

If clients make multiple POST calls for the same user, what are the recommended options in this scenario? Success with an existing resource id? or an error? or something else.

One important thing to remember is that, on an unreliable network, the client cannot distinguish between a lost request and a lost response. So you will probably benefit from having a clear protocol in place to handle that condition.

Idempotent request handling is probably your best bet: tell the client that the user was created successfully as many times as it takes.

There's an edge case where you get two messages with the same unique identifier, but the other data is different, and you should work through the protocol to figure out the correct behavior in that case (first writer wins? last writer wins? raise a conflict?) keeping in mind that you have no guarantees that requests arrive in the order that they were sent.

Note: because you are using POST, general purpose components will not know that the request is idempotent, and won't be able to take advantage of that, which is fine. A resource model that supports PUT, rather than POST, would allow the general purpose components to handle lost messages, but there are other trade offs (for instance, HTML forms don't support PUT).

Community
  • 1
  • 1
VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91