Reputation: 10219
I'm building an API where the majority of endpoints accept and return multiple resources. I'm having trouble determining whether to use POST or PUT requests.
In my situation, resources are always created and identified outside of the API using UUIDs for identifiers. Since the resources already exist and are already identified, a PUT request seems appropriate. However, it would be impractical to include the UUID of each resource in the URI (the UUIDs are very long and there could be many resources in a single request).
A POST request also seems appropriate because even though the resource is already identified with an ID, it does not yet exist in our database. Also, with POST requests, there is no expectation of having the IDs in the URI.
Which would be the correct HTTP verb to use in this situation?
PUT /resources/1,2,3 ---> Impractical due to the number of resources per request
PUT /resources ---------> More practical but lacks IDs in the URI
POST /resources ---------> Possibly inaccurate verb since resource is already identified
Upvotes: 3
Views: 1502
Reputation: 13672
Your three choices, as I see them, are:
Use PUT /resources/1
, then PUT /resources/2
, then PUT /resources 3
. This is the "as designed" approach. It does result in 3 calls instead of 1, but lets you leverage the benefits of using PUT
.
Use POST /resources
, with the body of the POST
containing all details on all the resources going up to the server, including the id. The server can create the resource from the id in the body. You lose the benefits of PUT
, but save on wire traffic.
Use PATCH /resources
, with the body of the PATCH
containing all details on the resources to be created. This really only works if you're using JSON, since patch semantics for XML are iffy at best. The semantics are described in RFC 6902.
It is generally not suggested to perform a request on multiple ids. If you call PUT /resources
, semantically you're saying that you're replacing the contents of /resources
with the body you just sent up, which is not what you intend.
I would suggest the first approach unless you have a proven reason to avoid it (tested and have a performance issue). In that case, I'd seriously consider PATCH
over POST
.
Upvotes: 4