Monday, May 6, 2013

Use HTTP Options to query whether a RESTful resource can be created

My colleagues and I ran into a problem about how to check whether a RESTful resource can be created before sending the HTTP POST to create the resource.  The use case is that there is a business requirement setting a limit on how many resources can be stored for a user.

For example, a bank may limit the number of accounts a customer can open. It would be a bad user experience if we allow a user to type information about a new account and hit submit to see an error that the maximum number of accounts has been reached.

Request: HTTP POST /customers/xxx/accounts
Response: HTTP 400 Bad Request with 'Maximum number of accounts has been reached' error message. 

We decided to make a request to check whether a new account resource can be crated before we ask users to enter information. We explored a couple of options. One is to define a new endpoint to query whether a new resource can be created.

Request: HTTP GET /customers/xxx/accounts/can_create
Response: 200 OK or 400 Bad Request 

However, this seems to introduce another verb to the resource. One of my colleagues referred me to HTTP Options and it works perfectly for this use case.

HTTP Options checks whether what HTTP verbs we can operate over the resource URI.  It is specified in the 'Allow' response header.  So if we see that we can POST to the resource, it means that we can create the resource.

Request: HTTP OPTIONS /customers/xxx/accounts
Response: 200 OK
                 Allow: HEAD,GET,POST,PUT,DELETE,OPTIONS
Using HTTP Options allows us to query possible actions we can do with resources without requiring a new end point or payload.  I wish it was mentioned more often in other RESTful resources.