How to build REST API?

I am new to REST.I have knowledge with PHP SOAP web service. There we have a SOAP Server PHP File which has all functionality and a WSDL file describe the functions and parameteres . Then the client can communicate to SOAP server via wsdl file from his code any where.

Like the way continous from this question please tell how REST become? what may be the server file and how the client communicate to REST server? using curl or any other way ? Give me some sample codes much better to understand.

Thanks in advance.


  $service_url = 'http://example.com/rest/user/';
   $curl = curl_init($service_url);
   $curl_post_data = array(
        "user_id" => 42,
        "emailaddress" => 'lorna@example.com',
        );
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($curl, CURLOPT_POST, true);
   curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
   $curl_response = curl_exec($curl);
   curl_close($curl);

now if need response in xml then try this

$xml = new SimpleXMLElement($curl_response);

or in json

$json = json_encode($curl_response);

I'm not really sure what you are trying to get more then the question you linked.

The thing with a REST server is that you could start to understand it as a bunch of URLS (possibly with parameters) that do stuff.

Stuff is defined by either retreiving your data, inserting your records, etc etc. The parameters can be GET parameters or POST parameters, using the standards from the HTTP definition.

Using the service

What you do in the end is communication by HTTP. You request a resource from your REST service (for instance http:://yoursite.tld/user/id1, http://yoursite.tld/user?id=1, etc to get user 1) any way you would normally. Be it Curl, be it wget, be it java http object, just do a HTTP request. The same goes for changing that user (you could imagine using a POST here).

making the service

Just like a website you can make a service by creating anything that can parse these requests, and send back information. THe thing is, there is no central method / WSDL etc like in SOAP (both the strength and weakness of REST). Just make sure you can serve your data when a request is done, be it with a special file per request, a central index that redirects your requests, some .htaccess redirect trickery.

A simple method would be to use either a framework or some standard you yourself made. YOu can image your requests looking like /yourCommand/yourMode/yourData where the first part tells your system what function / object / file to call, then the mode tells it what to do, and finally the data is what you need (for instance the ID of the user). You requests might look like /user/get/1 to retreive a user.

链接地址: http://www.djcxy.com/p/46196.html

上一篇: 为什么它不起作用? JSON,AJAX,PHP

下一篇: 如何构建REST API?