Kookz Kookz - 2 months ago 11
reST (reStructuredText) Question

POSTing to a Single Item vs. Collection (REST API)

Say I have a REST API with endpoint

. POSTing a user to that endpoint would create a new user and add it to the existing collection, give the user a unique ID so that you can work with it. If I make a
GET /api/users/1
, this should return me the created user with id: 1. My question is what should be the case for POSTing to a single item instead. For POSTing to a collection, you should return
201 Created
if the resource was created, or a
409 Conflict
if the resource already exists. What is the best practice for POSTing to a single resource ? Should it return a
405 Method Not Allowed
, as you shouldn't be allowed to POST to a single resource or should it return a
404 Not Found
as described here ?


If, at the moment a request is received, a resource (regardless of the concept that it represents) does not support a particular method (POST), the correct response to return is 405

The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. The origin server MUST generate an Allow header field in a 405 response containing a list of the target resource's currently supported methods.

The HTTP Specification includes a method (OPTIONS) and response headers (Allow) that enable a client to interrogate a server to discover what methods are permitted. Adoption might be lacking, although I suppose CORS changes that.

Note: there are use cases where POST to a singular resource is a reasonable option (consider how you would define the protocol to star a responsitory in an api where HTML was your hypermedia format). In that case, you should choose the appropriate success code (200, 201, 204...), assuming things went well, of course.