Nobody likes having to work with SOAP APIs, but we don't always get a choice. So why hasn't anybody done anything about it yet? Soap is a plug-and-play package for Laravel that makes SOAP (dare I say) enjoyable to work with in your applications. If you've worked with the Http client introduced in Laravel 7, you'll feel right at home.
Making your first Soap request is simple using the provided Soap
facade:
1$customers = Soap::to('https://api.example.com')2 ->withBasicAuth('username', 'password')3 ->Customers(['SortBy' => 'name']);
Faking Requests
One of the biggest challenges developers face when working with SOAP APIs is mocking requests and responses for unit tests
or local development. With the Soap package, all of those challenges disappear:
1Soap::fake( 2 'http://api.example.com:Customers' => Response::new([['name' => 'Garry'], ['name' => 'Bob']]) 3); 4 5// This request will now return our requested response 6$customers = Soap::to('https://api.example.com')->Customers(['SortBy' => 'name']); 7 8// When faking, you can perform inspections on requests too! 9Soap::assertSent(function($request, $response) {10 return in_array('Garry', $response->response);11});12 13Soap::assertSentCount(1);
Using Hooks
Almost every SOAP API has some strange quirk that you need to factor in. It can be frustrating to require messy conditional logic to normalize the data in your code. With the Soap package, you can move all of that logic out of the way using hooks.
For example, imagine that the SOAP API you're using requires a Version
parameter with each request. You don't want to include that manually in each location you call the API. Instead, you can place a global hook that will fire before each request to include the Version
parameter automatically.
1// AppServiceProvider2 3public function boot() {4 Soap::beforeRequesting(function($request) {5 $request->set('Version', config('example-soap-api.version'));6 });7}
Debugging with Ray
Want to debug a SOAP request in your application. The Soap package ships with support for Spatie's Ray debugging app. Just callray()->showSoapRequests()
, and you'll get a nicely formatted table with the endpoint, method, request, and response body in the Ray app every time a new SOAP request gets made.
0 comments:
Post a Comment
Thanks