Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful way of getting a resource, but creating it if it doesn't exist yet

For a RESTful API that I'm creating, I need to have some functionality that get's a resource, but if it doesn't exist, creates it and then returns it. I don't think this should be the default behaviour of a GET request. I could enable this functionality on a certain parameter I give to the GET request, but it seems a little bit dirty.

The main point is that I want to do only one request for this, as these requests are gonna be done from mobile devices that potentially have a slow internet connection, so I want to limit the requests that need to be done as much as possible.

I'm not sure if this fits in the RESTful world, but if it doesn't, it will disappoint me, because it will mean I have to make a little hack on the REST idea.

Does anyone know of a RESTful way of doing this, or otherwise, a beatiful way that doesn't conflict with the REST idea?

like image 321
gitaarik Avatar asked Sep 24 '13 08:09

gitaarik


People also ask

Which REST request method is used to create a resource?

POST is the only RESTful API HTTP method that primarily operates on resource collections. When creating a subordinate resource in a collection, applying POST to the parent resource prompts it to create a new resource, associate it with the proper hierarchy and return a dedicated URL for later reference.

Does Put create a new resource if it doesn't exist?

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.

What happens when you send PUT request but the resource does not exist?

If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response.

What are RESTful resources?

Resources are the basic building block of a RESTful service. Examples of a resource from an online book store application include a book, an order from a store, and a collection of users. Resources are addressable by URLs and HTTP methods can perform operations on resources.


1 Answers

very simple:

  1. Request: HEAD, examine response code: either 404 or 200. If you need the body, use GET.
  2. It not available, perform a PUT or POST, the server should respond with 204 and the Location header with the URL of the newly created resource.
like image 114
Michael-O Avatar answered Nov 15 '22 09:11

Michael-O