I’m working on my first web application and have this basic doubt.
I have a group of posts and I want to allow users to vote on them. I’m working with PHP so I have an article.php script with code that handle HTTP requests.
At the moment I implemented article creation which uses data sent through a POST HTTP request (using html form). The article id returned is the one I get from the DB storing articles.
Similarly, I handle GET requests and return an article based on the id sent as a parameter. If no parameter is defined, I return a list of all articles.
For the moment I haven’t done any url rewrite so requests are of the form article.php?id=xxx
Now I want to implement votes, and this is where I’m facing a problem. According to REST, I should use POST on a specific resource (given that votes aren’t idempotent) so I’d send a POST request to /article/1234 with a body "+1" for a positive vote.
The question is, how do I map the above to my use case? Assuming url rewrite was made, what would that translate to? Doing a rewrite to article.php?id=1234 wouldn’t work because POST doesn’t take parameters in the URI (AFAIK).
And also, how would I distinguish this action from any other? Should I also add some “action” parameter like article.php?id=1234&action=vote?
It seems as did not get the real idea of a REST-ful application. Retrieving the articles with GET and edit it with POST is fine, but you have to expand this to votes. REST-ful applications assume that one url identifies one resource. So, you have to think of votes as an own resource (that are related to articles).
So, your application should work like this
GET article.php/id/1: retrieve the article with id 1
POST article.php/id/1: alter the artcile with id 1
GET article.php/id/1/votes: retrieve the votes of the article with id 1
POST article.php/id/1/votes: alter the votes of article with id 1
Its completely fine to implement the latter one with adding one up-vote, as long as votes are implemented as a simple counter.
You may redefine this logic by giving the votes identity, e.g. if you want to add more attributes to a vote like the user who made the vote.
As you asked for the rewrite and if an application is able to get data from the url with a post-request: Yes, thats completely possible. A POST request to article?id=1 will have $_GET[‘id’] available.
The rewrite-part as shown above is completely optional. REST is not interested in the “niceliness” of a url as long as ONE url identifies ONE resource.
Hopefully this gave you an idea of how to continue