SOAP APIs Tutorial
Introduction to SOAP
SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured information in the implementation of web services. It relies on XML for its message format and usually relies on other application layer protocols, most notably HTTP and SMTP, for message negotiation and transmission.
Why Use SOAP?
SOAP is designed to be platform-independent and operates over a wide range of protocols such as HTTP, SMTP, TCP, etc. It is also known for its high level of security and extensibility, making it suitable for enterprise-level web services.
SOAP vs. REST
SOAP and REST are two different approaches to web services. While SOAP is a protocol with extensive standards and security features, REST is an architectural style that uses standard HTTP methods. SOAP is generally used in scenarios requiring high security and complex transactions, while REST is preferred for its simplicity and performance.
Setting Up a SOAP Web Service in PHP
PHP provides built-in support for SOAP through the SoapServer
and SoapClient
classes. Let's create a simple SOAP web service to demonstrate how it works.
Creating a SOAP Server
First, we will create a PHP script to act as our SOAP server:
<?php class Calculator { public function add($a, $b) { return $a + $b; } public function subtract($a, $b) { return $a - $b; } } $options = array('uri' => 'http://localhost/'); $server = new SoapServer(null, $options); $server->setClass('Calculator'); $server->handle(); ?>
Save this file as server.php
. This script defines a simple calculator class with methods for addition and subtraction, sets up a SOAP server, and handles incoming SOAP requests.
Creating a SOAP Client
Now, let's create a client to consume the SOAP web service:
<?php $options = array( 'location' => 'http://localhost/server.php', 'uri' => 'http://localhost/' ); $client = new SoapClient(null, $options); try { $result = $client->add(3, 2); echo "3 + 2 = $result\n"; $result = $client->subtract(5, 3); echo "5 - 3 = $result\n"; } catch (SoapFault $fault) { echo "Error: {$fault->faultcode}, {$fault->faultstring}\n"; } ?>
Save this file as client.php
. This script sets up a SOAP client, calls the methods defined in the calculator class on the server, and prints the results.
Running the SOAP Service
To run the SOAP service, follow these steps:
- Start a PHP built-in server from the command line:
- Open another terminal and run the client script:
php -S localhost:8000
php client.php
The client will output the results of the SOAP calls to the console:
5 - 3 = 2
Conclusion
In this tutorial, we covered the basics of SOAP APIs and demonstrated how to create a simple SOAP web service in PHP. SOAP provides a robust and secure way to implement web services, particularly in enterprise environments.