Using HTTP PUT and DELETE methods in web applications

I've been thinking about how to make an application I'm currently designing more REST-like. (You'll forgive me if I avoid the atrocious neologism "RESTful.") The HTML forms specification only supports the GET and POST methods for form submission, but if you've ever designed a web service for other HTTP clients, you've probably had a good reason to use PUT and DELETE as well. PUT is an idempotent create operation; sending the same PUT twice will cause the same resource to be created at the same URI, whereas a duplicate POST could have unknown, possibly disastrous side-effects. And HTML forms have no support at all for anything resembling DELETE -- how often have you designed an application that requires a POST to delete an object? That doesn't make sense.

When designing applications for use by other HTTP clients, you can use whatever HTTP methods you want. But designing applications for the web is harder, especially if you want it to be usable by both web browsers and other types of clients.

There are a couple ways to get around this limitation.

One is to use AJAX. The XMLHttpRequest object, unlike HTML forms, supports any HTTP method. But AJAX isn't always practical; you may have clients without Javascript support, and it may just not be worth it to write Javascript code for a very simple form submission.

So I am experimenting with "tunneling" other HTTP methods through POSTs. For example,

<input type="hidden" name="http_method" value="PUT" />

On the server side, I'm thinking of doing something like this when constructing the CGI query object in my CGI::Application class.

sub cgiapp_get_query { 
    my $q = CGI->new;
    if ( $q->request_type eq 'POST' and my $method = $q->param( 'http_method' ) ) { 
        $ENV{REQUEST_TYPE} = $method;

Then, in my runmode methods, I can check $q->request_type (which just looks at $ENV{REQUEST_TYPE} anyway) and it will be 'PUT'. This should work whether it's a real PUT executed by a non-browser HTTP client or a "fake" PUT from a form submission.

ETA: I accidentally deleted some comments while playing around with the admin interface. Oops.

1 Comment

Leave a comment

About Mike Friedman

user-pic Mike Friedman is a professional computer programmer living and working in the New York City area.