views:

372

answers:

2

Hi can anyone past some code how to do a restful web service get and post method. This would be server side so I would be able to invoke the two services from a client.

Thanks!

A: 
POST:
<?
// Helloworld_post.php
echo "Hello world <pre>"
print_r($_POST['data'];
?>

GET
<?
//helloworld_get.php
echo "Hello world <pre>"
print_r($_GET['data'];
?>

What exactly are you trying to do? You need to use mod_rewrite or its equivalent to make pretty /helloworld/ urls. The beauty of REST is it is just a standard http request. It doesn't specify json encoding or xml encoding or "wtf I am the 1337" encoding.

Byron Whitlock
+2  A: 

Assume you have a script index.php. You might have two functions inside of it, showForm() and handleForm().

Assume a request comes in to index.php.

if (! empty($_SERVER['REQUEST_METHOD'])) {
    if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
    {
     doSomething();
    }
    else
    {
     showSomething();
    }
}

There you have it. REST. If you send a GET request to index.php, you'll show some output, and if you send a POST request to index.php, you'll perform some data manipulation. You can take if from there for the other RESTful HTTP request types, such as DELETE, etc.

Obviously this is a very simple example, and I wouldn't want to create an entire site in this manner. It's best to go about creating a RESTful site in an architecturally sound way. Many frameworks can assist with this.

REST is a hot topic right now, it seems everyone wants their apps to be RESTful. There's a lot of articles and guides out there on Google, you'd probably do well to spend some time researching various approaches.

Note about URLs: URIs don't have to be pretty to be RESTful. However, a key point of REST is that all URIs should represent a single resource. As query parameters are not part of a URI, "/index.php?show=2" is not considered RESTful. You'll find that a lot of applications use URL rewriting to convert query parameters into something like "/index/2" instead.

That being said, there's nothing wrong with having "/index.php" as a URI, just as long as it only represents a single state.

zombat