Creating RESTful Websites with HTML Forms

rest

Let's say that I want to create a website where users will be able to create, edit and delete some kind of resources, for example posts.

I have created a RESTful API, so user can create a post by sending a PUT request to http://www.example.com/posts/my-new-awesome-post, delete it by sending DELETE request, etc.

But most users don't know anything about HTTP requests. They want to click a "New post" button and have the new post created. But HTML only allows me to use GET and POST.

How can I create a "New post" button that will send a PUT request? Or is "RESTful creation/deletion" implemented in a totally different way?

Let's say I'm using Spring + Thymeleaf.

Best Answer

The 'New Post' button would go to a form for the user to input the information for a new post. When the user submits that form the browser rightly sends that data via HTTP POST (use POST for create).

An edit submission would use PUT or PATCH depending on whether it is a replace (delete the missing properties) or update (only change the submitted properties), respectively.

We usually make an XMLHTTPRequest (XHR) using JavaScript for events other than GET or POST.

jQuery.ajax('/products/42', {method: 'PUT', data: product_data});

jQuery Docs: http://api.jquery.com/jquery.ajax/

Additionally, Rails will use a '_method' param in POSTs to force a different action on the server ( like PUT or PATCH).

Related Topic