The following article is a short snippet from the "Building an API Integration Using Saloon" chapter of my book "Consuming APIs In Laravel".
The book teaches you how to write powerful and robust code to build API integrations in your Laravel apps. It's packed with over 440+ pages of actionable advice, real-life code examples, and tips and tricks.
In the book, I teach you how to write code that can help you sleep easy at night having confidence that your API integration works!
What is Saloon?
Saloon is a PHP library created and maintained by Sam Carré that allows you to easily consume APIs in your PHP applications.
It uses an elegant, expressive, object-oriented approach that makes it easy to build API integrations without worrying about the underlying implementation. Saloon has many features that make it easy to build API integrations, such as authentication handling, concurrent requests, pagination, error handling, and caching.
It ships with handy default settings that make it easy for you to get started. But it also allows you to customize these settings to suit your needs.
A key benefit of Saloon is that it comes with powerful tools you can use for writing tests for your API integrations. This makes it simpler to write tests that are easy to read and maintainable.
Saloon is also an excellent choice for consuming APIs in your Laravel applications as it encourages you to abstract your code into classes, such as "connectors" and "requests", which we'll cover later in this chapter. By logically separating the code, it makes it much easier for you to maintain and extend your integrations in the future.
This chapter will focus on using Saloon v3. Specifically, we'll be using Saloon's Laravel driver, which allows us to easily integrate Saloon into our Laravel application by providing features such as:
- Artisan commands for creating new connectors and request classes
- Facade for mocking and recording requests for testing
- Access to Laravel's
HTTPsender rather than the defaultGuzzlesender
Alternatives to Saloon
If you're building an API integration for your Laravel application, you can take several approaches to making HTTP requests. Let's take a quick look at some of the alternatives to Saloon:
Guzzle
Guzzle is a popular PHP HTTP client that you can use to make HTTP requests. It's a great choice for making API requests, especially as it ships in the default installation of Laravel, so it doesn't require you to install any additional dependencies.
It is relatively straightforward to use and also has tools that you can use for mocking responses in your tests.
The core Saloon package actually uses Guzzle under the hood to make HTTP requests.
An example request using Guzzle may look something like this:
1$client = new GuzzleHttp\Client(); 2 3$response = $client->get('https://api.github.com/user', [ 4 'headers' => [ 5 'Authorization' => 'Bearer '.config('services.github.token'), 6 ] 7]); 8 9$statusCode = $response->getStatusCode();10// $statusCode is: 20011 12$contentType = $response->getHeader('content-type')[0];13// $contentType is: "application/json; charset=utf-8"14 15$contents = json_decode(16 json: $response->getBody()->getContents(),17 associative: false,18 depth: 512,19 flags: JSON_THROW_ON_ERROR20);21// $contents is: {"login": "ash-jc-allen", ...}
Http Facade
The Http facade is a class that ships with Laravel that you can use to make HTTP requests. It's a wrapper around Guzzle that simplifies some of Guzzle's functionality and makes it easier to use.
In my opinion, the Http facade provides two main benefits over using Guzzle directly:
- The
Httpfacade includes many methods you can use for testing. It allows you to mock the responses for individual calls and inspect HTTP requests to ensure your application sends them with the correct data. - All the requests made via the
Httpfacade can be logged in Laravel Telescope (a package that provides a dashboard for debugging and inspecting your Laravel application). This makes it easy to visually inspect your requests and responses and debug any issues you may have.
As a side note, if you'd like to log your HTTP requests made by Saloon, you can install the saloonphp/laravel-http-sender package and configure Saloon to use the Http facade as the sender rather than Guzzle. We'll cover how to do this in more depth later in this chapter.
Continuing with our GitHub example from earlier, an example request using the Http facade may look something like this:
1$response = Http::withToken('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') 2 ->get('https://api.github.com/user'); 3 4$statusCode = $response->status(); 5// $statusCode is 200 6 7$contentType = $response->header('content-type'); 8// $contentType is: "application/json; charset=utf-8" 9 10$contents = $response->json();11// $contents is: {"login": "ash-jc-allen", ...}
As we can see, the Http facade hides away some of Guzzle's functionality for us to keep the code understandable and easy to read. For example, instead of needing to call getBody()->getContents() to get the response body and then using json_decode, we can simply call json() to get the response body as an array.
cURL
Another option that you can use to make HTTP requests is "Client for URL" (cURL). PHP supports libcurl, a library you can use to make different types of requests, such as HTTP requests.
In fact, Guzzle uses cURL under the hood to make HTTP requests by default because it's a powerful and flexible library that's been around for a long time and is typically available on servers. This means that when using Saloon, you're indirectly using cURL under the hood.
However, although cURL is a powerful tool, it is a lot of work to use and can be verbose. For example, take our example GitHub request and write it using cURL:
1$ch = curl_init(); 2 3curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/user'); 4curl_setopt($ch, CURLOPT_HTTPHEADER, [ 5 'Authorization: Bearer '.config('services.github.token'), 6 'User-Agent: My-Laravel-App' 7]); 8curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 9 10$output = curl_exec($ch);11 12if(curl_errno($ch)){13 echo 'Curl error: ' . curl_error($ch);14} else {15 $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);16 // $statusCode is 20017 18 $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);19 // $contentType is: "application/json; charset=utf-8"20 21 $contents = json_decode($output, false, 512, JSON_THROW_ON_ERROR);22 // $contents is: {"login": "ash-jc-allen", ...}23}24 25curl_close($ch);
We can see that it's a lot more verbose than the Guzzle and Http facade examples. This makes it harder to read, understand, and maintain. A general rule I like to follow when writing code is to make it read like an English sentence as much as possible. The more plain English is used, the easier it will be for new developers to understand the code, and the easier it will be for me to understand it in the future. I don't feel cURL helps achieve this goal.
You're unlikely to encounter cURL requests in your Laravel applications, but if you're working on an older application with some legacy code, you may encounter it.
API SDK
Sometimes, you must build an API integration for your Laravel application and find that the third-party service has a software development kit (SDK) available. In the context of PHP applications, an SDK is typically a Composer package you can download and install into your application that provides a wrapper around the API you're integrating.
For instance, imagine you want to interact with the Stripe API to take payments from your web application's customers. To do this, you may want to install Stripe's official PHP SDK (stripe/stripe-php). As a basic example, you could write the following code to create a new customer using the Stripe package:
1use Stripe\StripeClient;2 3$stripe = new StripeClient(config('services.stripe.secret'));4 5$customer = $stripe->customers->create([6 'description' => 'John Doe',7 'email' => 'john@example.com',8 'payment_method' => 'pm_card_visa',9]);
As you can see, the SDK provides a convenient wrapper around the API, making it easy to interact with and removing the need to worry about the underlying HTTP requests and responses. This way, you can focus on the business logic of your application.
Generally, SDKs are built and maintained by the third-party service companies themselves. They act as a way to encourage developers to integrate with their API and make it as easy as possible to do so — they're essentially a marketing tool. For this reason, they're typically well-maintained and kept up to date with the latest API changes. Thus, you don't need to worry about keeping up to date with the API changes yourself, as the SDK will do this for you. You'll have the added benefit of the SDK including tests to ensure it works as expected. So, you can write your own tests to ensure that the SDK's methods are being called correctly without needing to test the underlying HTTP requests.
However, I strongly recommend inspecting an SDK before you start using it. As mentioned, these packages and libraries are a marketing tool for third-party services. As with any other aspect of business, building and maintaining them costs money. If the package isn't especially popular, it may not be well-maintained. If this is the case, you may find that the SDK is outdated and doesn't support the latest API changes. This could cause issues for your application and may mean that you must write your own wrapper around the API.
To help decide whether you should use an SDK, here are several questions to ask when inspecting it:
- How many downloads does the package have? - This isn't a perfect metric, but it can give you a good idea of a package's popularity. It's likely to be well-maintained and updated if it has many downloads. It can also indicate that more people have been using it, meaning there's an increased chance bugs have been spotted and fixed. It's likely not very popular and may not be maintained very much if it has very few downloads.
- How many open issues does the package have? - Check out the issues for the package and see what types of problems you're seeing. Many issues may be feature requests, which aren't necessarily alarming. The issues you want to look out for are things like "this package doesn't work with the latest version of the API" or "this package doesn't work with the latest version of PHP". These issues can indicate that the package isn't well-maintained.
- How many open pull requests does the package have? - If there are open pull requests to fix bugs or add new features, this indicates community interest. Note the frequency of recent merges and whether minor fixes have been ignored for long periods to gauge maintainer activity.
Should I Use Saloon?
When planning your API integration, you might ask, "Should I use Saloon, Guzzle, the Http facade, cURL, or the API SDK?". That's a valid question you'll need to answer based on your project's needs.
Let's start by saying it's doubtful that you'll want to use cURL directly. Although it's a very powerful library, and you'll be interacting with it regardless of the other options you choose, it's not very easy to use and can be quite verbose. It's also not very easy to test compared to the other approaches, making it difficult to write tests for your application. It's important to remember that we must ensure that tests are easy to write. The easier they are to write, the more motivation you'll feel to write them. If tests are difficult to write, you'll be less likely to write them, which means you'll have less confidence in your application.
You may want to use Guzzle or the Http facade to build your integration. These are both perfectly valid approaches and ones I've used many times. They both have testing utilities and come packed with many convenient methods to simplify sending requests and reading responses. Of these two approaches, I would lean more towards the Http facade as it makes the code look cleaner and more readable — and readability is very important. If you're only going to send a single API request in your application, you may want to use one of these rather than installing Saloon. Sam Carré, the creator of Saloon, has stated in the past that it may be easier to use one of these approaches rather than installing a new dependency (Saloon) and keeping it up to date in your application.
If the third-party service you're using offers an SDK for interacting with their API, you may want to opt for that. This is, of course, assuming that it's well-maintained and that you're happy with the quality of the code. Using their package, you can take advantage of the code they've written. This will also reduce the burden of updating your code with the latest API changes.
If there isn't a well-maintained SDK available, you can use the Saloon package. Saloon allows you to use an object-oriented approach to building your integration code with small, focused classes that are highly testable. You'll also have access to Saloon features such as caching responses, error handling, OAuth handling, plugins, and more. You can take advantage of all these features to build very extensive integrations.
Another benefit of Saloon is its popularity and the fact that it's well maintained. As mentioned, it's important to ask questions before installing a new dependency in your application. You want to make sure that it's still actively being maintained and that it will be around for a long time. At the time of writing, Saloon boasts over 460k downloads (averaging at around 60k downloads per month), 1.6k stars on GitHub, and has had over 80 releases. The package also has a good-quality test suite with a high level of code coverage. These are all good indicators that the package is well maintained and is safe to use in your application.
As a side note, you can also use Saloon to build your own API SDK. You may want to do this if you're building an API service and want other developers to start using it.
No matter which of these approaches you take, I recommend writing a thin abstraction layer over your code. You can do this using interfaces and dependency injection, as we've already covered in the "Code Techniques" section. Doing this can make it easier to switch out your implementation in the future. For example, imagine you have written your API integration using an SDK that is now abandoned and won't receive any more updates. You may want to use Saloon to rewrite the API calls and logic in this situation. If the code is abstracted away behind interfaces, you'll be able to swap out the implementation without needing to change any of the code that uses the API integration. This is a very powerful technique and one that I recommend using.
Want to Continue Reading?
Hopefully, this snippet from the book has given you a good overview of Saloon and how it compares to other approaches for building API integrations in your Laravel applications.
If you've enjoyed it, you might be interested in reading the rest of the book which goes a lot more in depth about APIs and Saloon.
The book teaches you how to write powerful and robust code to build API integrations in your Laravel apps. It's packed with over 440+ pages of actionable advice, real-life code examples, and tips and tricks.
In the book, I teach you how to write code that can help you sleep easy at night having confidence that your API integration works!
👉 Make sure to use the discount code ASHALLEN20 to get 20% off!