What is the right way to define a generate endpoint in REST?

Viewed 92

I'm working on building a REST API and I'm not too sure what the correct way is to represent an endpoint that generates data. Assuming the ressource is about "items", I have the usual endpoints:

  • GET /items => list items
  • POST /items => create a new item
  • GET /items/{id} => get an existing item
  • PUT /items/{id} => update an existing item
  • DELETE /items/{id} => delete an existing item

Now, I also have a process that can generate items based on some parameters or configuration in the system. What is the correct way to define this endpoint with REST?

I am tempted to use also POST /items but this one is already taken to create a "single" new item. Is is correct to sometimes use:

  1. POST /items?from=2020-07-15&to=2020-07-21 for with no body => this creates a list of items
  2. POST /items with an item in the body => this creates a single item

Thanks for your input!

2 Answers

It is perfectly acceptable in REST to overload POST.

You might image on the web having two different forms, that promise to do different things, that share the same action uri. Browsers will do exactly the right thing - taking the input fields of the form, composing the body of the request, and then sending the resulting POST request using the same target-uri.

So long as the server can distinguish between the two meanings using the payload, there is no difficulty.

POST is, in general, the right answer any time you are doing anything other than remote authoring. See Fielding 2009: It is okay to use POST.

From the perspective of the client, the target-uri doesn't matter much, so if you want to create a different resource to handle the bulk creation use cases, that's OK too. The main reason that we might care about using

POST /items

is that doing so successfully will automatically invalidate the previously cached representations obtained via

GET /items

That would definitely be a POST. You can have POST /item with and item body and then have something like POST /item/batch?param=1&param=2 to mass-generate items based on the parameters you're passing.

Related