0

Most examples of RESTful APIs assume you are dealing with collections of things, e.g.

POST /books/ - create a book

GET /books/ - get a list of books

GET /books/1/ - get a particular book

However, there are some circumstances where you might want to create a singleton resource. For example, a new user might want to create a profile relating to themselves, the authenticated user.

POST /profile

PUT /profile

Is there any convention about how to create such singleton resources? i.e. using POST vs PUT. In terms of whether to use POST or PUT, does it make a difference if the resource can be modified after creation? Does the idempotency requirement of PUT require that it must be possible to update the resource after it is first created?

samfrances
  • 3,405
  • 3
  • 25
  • 40

1 Answers1

0

Remember that in REST a "singleton" resource doesn't mean there's only one instance of the resource in the system, it just means retrieving a single object rather than a list of objects.

A resource can be a singleton or a collection. For example, “customers” is a collection resource and “customer” is a singleton resource (in a banking domain). We can identify “customers” collection resource using the URN “/customers”. We can identify a single “customer” resource using the URN “/customers/{customerId}”.

(Thoughtworks, Rest API Design: Resource Modeling)

Standard practice would be for the client to POST to /profiles/, receiving the URL of the newly created profile (probably /profiles/<id>) in the Location: header of the response.

Alternatively, the client could PUT to /profiles/<some client-specified-ID>, receiving 403 Forbidden if the ID is already taken by another user. (Possibly 405 Method Not Allowed, if the other user's profile would be GET-able.)

On the reading side, it's not common to model the concept of "my profile", with an unknown ID, in a RESTful API. If you really need it, probably the RESTful thing to do is advertise the (identified) URL in a link from the root resource, with a custom link relation.

Community
  • 1
  • 1
David Moles
  • 48,006
  • 27
  • 136
  • 235