Sahil Sharma
Sahil Sharma

Reputation: 4217

Is it considered RESTful if single POST requests create multiple resources?

We have customers API that takes {customer-name, customer-mobile, customer-email} and creates customer in the database.

We also have order API that takes {productId, customer-name, customer-mobile, customer-email}.

The code for order API:

  1. First creates customer based on {name,mobile,email} passed in the order API and return back customerId.
  2. The {productId, customerId} further gets saved in the database in the order table.

Is this restful practice that one API is internally first creating some other resource?

Please note that its an over simplified example where API expects only one type of product in the order API.

Upvotes: 3

Views: 1995

Answers (1)

sisyphus
sisyphus

Reputation: 6392

It's fine for a single POST call to result in multiple resources being created. It's not generally the best idea but there are use cases where it makes sense - example cases might include (usual legal disclaimer... not limited to...)

  • the POST method is to the parent resource of all the created resources. So, a POST /accounts call might result in an /accounts/<accountId> resource being created but also an /accounts/<accountId>/tweets resource. In this instance, the /accounts/<accountId> parent is the 'actual' resource being created.

  • the POST method might create multiple resources representing multiple ways in which the resource may interact with other parts of the system. So, a POST /accounts response might create resources under /accounts/<accountId> and /users/<accountId> (because an account is-a user and user id are a super set of account ids, for arguments sake). However, the client really only gets told about the one under the '/accounts' path (via the Location header). The other created resource is basically a side-effect.

The key point, really, is that the POST method returns a single Location header - representing the 'primary' resource created - and that subsequent 'GET's on that URI are capable of locating any the other resources via links.

If you find yourself in a situation where creating multiple resources via a single POST request results in you having to return different values for the Location header, then something's wrong with your resource breakdown. It should be clear that a 'POST' will always create one particular type of resource, a URI to being returned in the header. Other resources might be created as side-effects.

Upvotes: 3

Related Questions