Steve McDougall Avatar
Published on

Working with third party services in Laravel

Authors
Working with third party services in Laravel

I have been working with 3rd party APIs for longer than I care to admit, over time I have found a few ways that work nicely for me. In particular when working with a Laravel application, it is always good to define a standard for how you do things. Not only is this good practice in general, but it also makes it predictable when you are trying to add or update or debug anything. By following a standard, you know how your projects work from one to another.

In this article, I am going to walk through how I connect and work with 3rd party APIs - what has worked for me and how I like to approach this task. I am going to walk through how to connect to the PingPing API in your Laravel project, and how you can use it to start getting the monitoring information from your websites.

This article is using Laravel 8 and PHP 8, please do not follow this exactly if you are on lower versions - you will have to slightly adapt.

Firstly, set up a new Laravel project, or use an existing one if you want to add a service onto your existing app. What we need to do is create a new namespace for where our 3rd party APIs will live. I typically store these under App\Services as it makes the most sense to me. From there we want to create the namespace for the API we are working with. Create another directory, so it should look like this: app/Services/PingPing.

The first thing we want to do in this directory is to create a Client that we can use to connect to the API, create a class called Client that looks like this:

1 
2namespace App\Services\PingPing;
3 
4 
5class Client
6{
7 
8 //
9 
10}

Next, we want to build up our constructor so that it accepts a few default parameters:

1public function __construct(
2 protected string $uri,
3 protected string $token,
4) {}

What we are going to do with this part, is use a Laravel Service Provider to pull some configuration options and pass them into the constructor when we resolve this class from the container.

In your terminal, create a new Service Provider like: php artisan make:provider PingPingServiceProvider. If all went well, you should now have a file under app/Providers/PingPingServiceProvider. Now we are going to add our Client into the register method so that we can register our Service into the container. Your Service Provider should now look like this:

1namespace App\Providers;
2 
3use App\Services\PingPing\Client;
4use Illuminate\Support\ServiceProvider;
5 
6class PingPingServiceProvider extends ServiceProvider
7{
8 public function register()
9 {
10 $this->app->singleton(Client::class, function ($app) {
11 return new Client(
12 uri: config('services.ping-ping.uri'),
13 token: config('services.ping-ping.token'),
14 );
15 });
16 }
17 
18 public function boot()
19 {
20 //
21 }
22}

As you can see from the service provider, we also need to add some config values to our config/services.php file and .env file:

1return [
2 'ping-ping' => [
3 'uri' => env('PING_PING_API_URI', 'https://pingping.io/webapi'),
4 'token' => env('PING_PING_API_TOKEN'),
5 ],
6];

Next we need to register our service into our Laravel application, by adding this Service Provider in config/app.php under 'providers':

1return [
2 'providers' => [
3 /*
4 * Application Service Providers...
5 */
6 App\Providers\AppServiceProvider::class,
7 App\Providers\AuthServiceProvider::class,
8 // App\Providers\BroadcastServiceProvider::class,
9 App\Providers\EventServiceProvider::class,
10 App\Providers\RouteServiceProvider::class,
11 App\Providers\PingPingServiceProvider::class,
12 ],
13];

So, now we have a basic service set up. We have the environment variables and the config all sorted, we have a Client class which is registered into our container using our Service Provider. We have the beginnings of an API integration.

Our next step is to start working with the API. You can read the PingPing documentation here if you would like to, but I will walk you through it too.

Firstly, when working with 3rd party APIs, you want to be able to tests working against the API without sending loads of requests. In laravel you can use the Http facade and the fake() method to achieve this which is quite nice. However, I like to add this as a method on my Clients. To do this, I typically create a trait to handle this as I may be working with multiple APIs in an application - all of which need a fake method. I do this by creating a new directory under app/Services/Concerns to follow the Laravel naming convension for traits. Create one that looks like this:

1namespace App\Services\Concerns;
2 
3use Illuminate\Support\Facades\Http;
4 
5trait HasFake
6{
7 /**
8 * Proxies a fake call to Illuminate\Http\Client\Factory::fake()
9 *
10 * @param null|callable|array $callback
11 */
12 public static function fake(
13 null|callable|array $callback = null,
14 ): void {
15 Http::fake($callback);
16 }
17}

As you can see we are simply proxying the fake call through to the Http facade and forwarding any arguments along with them.

Now we just need to pull this trait into our Client class, and we can start faking requests:

1namespace App\Services\PingPing;
2 
3use App\Services\Concerns\HasFake;
4 
5class Client
6{
7 use HasFake;
8 
9 public function __construct(
10 protected string $uri,
11 protected string $token,
12 ) {}
13}

Now we are set up for testing our API, we can also start building up requests we may want to send. If you look through the documentation for PingPing you will see that you can get a list of monitors stored on your account quite easily. Let's start with this endpoint, and see how we may need to refactor as we go through.

Our first step is to create a new public method on our Client called monitors so that we can hit an API endpoint. Your method should look like this:

1public function monitors()
2{
3 $request = Http::withToken(
4 token: $this->token,
5 );
6 
7 $response = $request->get(
8 url: "{$this->uri}/monitors",
9 );
10 
11 if (! $response->successful()) {
12 return $response->toException();
13 }
14 
15 return $response;
16}

As you can see, we are building up our request with our API token that we injected into our constructor. We then create our response. There are a few things we can do to improve this though.

Currently the exception thrown is a HTML exception, which may not be what we want. Also, we have no retry policy or timeouts set. Lets refactor our Client class to implement these things:

1namespace App\Services\PingPing;
2 
3use App\Services\Concerns\HasFake;
4use Illuminate\Support\Facades\Http;
5 
6class Client
7{
8 use HasFake;
9 
10 public function __construct(
11 protected string $uri,
12 protected string $token,
13 protected int $timeout = 10,
14 protected null|int $retryTimes = null,
15 protected null|int $retryMilliseconds = null,
16 ) {}
17 
18 public function monitors()
19 {
20 $request = Http::withToken(
21 token: $this->token,
22 )->withHeaders([
23 'Accept' => 'application/json',
24 ])->timeout(
25 seconds: $this->timeout,
26 );
27 
28 if (
29 ! is_null($this->retryTimes)
30 && ! is_null($this->retryMilliseconds)
31 ) {
32 $request->retry(
33 times: $this->retryTimes,
34 sleep: $this->retryMilliseconds,
35 );
36 }
37 
38 $response = $request->get(
39 url: "{$this->uri}/monitors",
40 );
41 
42 if (! $response->successful()) {
43 return $response->toException();
44 }
45 
46 return $response;
47 }
48}

What we are doing now is passing some default values into our constructor so that we can set a default timeout, and how we want to handle any retries. We can now extend our service provider and config to include these values.

Extend your configuration to look like this:

1return [
2 'ping-ping' => [
3 'uri' => env('PING_PING_API_URL', 'https://pingping.io/webapi'),
4 'token' => env('PING_PING_API_TOKEN'),
5 'timeout' => env('PING_PING_TIMEOUT', 10),
6 'retry_times' => env('PING_PING_RETRY_TIMES', null),
7 'retry_milliseconds' => env('PING_PING_RETRY_MILLISECONDS', null),
8 ],
9];

Then extend your service provider to look like this:

1namespace App\Providers;
2 
3use App\Services\PingPing\Client;
4use Illuminate\Support\ServiceProvider;
5 
6class PingPingServiceProvider extends ServiceProvider
7{
8 public function register()
9 {
10 $this->app->singleton(Client::class, function ($app) {
11 return new Client(
12 uri: config('services.ping-ping.uri'),
13 token: config('services.ping-ping.token'),
14 timeout: config('services.ping-ping.timeout'),
15 retryTimes: config('services.ping-ping.retry_times'),
16 retryMilliseconds: config('services.ping-ping.retry_milliseconds'),
17 );
18 });
19 }
20 
21 public function boot()
22 {
23 //
24 }
25}

As you can see we are simply extending how we build our constructor to pull in the new values which we store in out env file - or providing the default NULL if we do not need this.

So back to monitors. We can now confirm we can get a Response back from the API, what can we do with it? This is where we have options, and the one we choose depends on what level of integration we need to build. For example, if we were building an SDK to provide to others we would simply return the Response and let the integrator decide how they want to work with the response in their application. But this is our application, and we are building an integration not an SDK.

What we want to do is using the Spatie Data Transfer Object Package create a series of Data Transfer Objects so that we can map the API response to Objects that are valuable to our application, and don't include lots of extra stuff that your typical HTTP request would have.

Let's start with an action to create our monitor under app/Services/PingPing/Actions/CreateMonitor.php that should look like this when complete:

1namespace App\Services\PingPing\Actions;
2 
3use Carbon\Carbon;
4use App\Services\PingPing\DTO\Checks;
5use App\Services\PingPing\DTO\Uptime;
6use App\Services\PingPing\DTO\Monitor;
7use App\Services\PingPing\DTO\UptimeMeta;
8use App\Services\PingPing\DTO\CertificateHealth;
9use App\Services\PingPing\DTO\CertificateHealthMeta;
10 
11class CreateMonitor
12{
13 public static function handle(array $item): Monitor
14 {
15 return new Monitor(
16 id: $item['id'],
17 identifier: $item['identifier'],
18 alias: $item['alias'],
19 scheme: $item['scheme'],
20 host: $item['host'],
21 port: $item['port'],
22 url: $item['url'],
23 statusPage: $item['status_page'],
24 checks: new Checks(
25 uptime: new Uptime(
26 id: $item['checks']['uptime']['id'],
27 status: $item['checks']['uptime']['status'],
28 error: $item['checks']['uptime']['error'],
29 interval: $item['checks']['uptime']['interval'],
30 enabled: $item['checks']['uptime']['is_enabled'],
31 notificationThreshold: $item['checks']['uptime']['notification_threshold'],
32 lastCheckAt: Carbon::parse($item['checks']['uptime']['last_check_at']),
33 meta: new UptimeMeta(
34 httpStatusCode: $item['checks']['uptime']['meta']['http_status_code'],
35 averageUptimePercentage: $item['checks']['uptime']['meta']['average_uptime_percentage'],
36 averageResponseTime: $item['checks']['uptime']['meta']['average_response_time'],
37 offlineSince: Carbon::parse($item['checks']['uptime']['meta']['offline_since']),
38 ),
39 ),
40 certificateHealth: new CertificateHealth(
41 id: $item['checks']['certificate_health']['id'],
42 status: $item['checks']['certificate_health']['status'],
43 error: $item['checks']['certificate_health']['error'],
44 interval: $item['checks']['certificate_health']['interval'],
45 enabled: $item['checks']['certificate_health']['is_enabled'],
46 notificationThreshold: $item['checks']['certificate_health']['notification_threshold'],
47 lastCheckAt: Carbon::parse($item['checks']['certificate_health']['last_check_at']),
48 meta: new CertificateHealthMeta(
49 issuer: $item['checks']['certificate_health']['meta']['issuer'],
50 signatureAlgorithm: $item['checks']['certificate_health']['meta']['signature_algorithm'],
51 selfSigned: $item['checks']['certificate_health']['meta']['is_self_signed'],
52 validFrom: Carbon::parse($item['checks']['certificate_health']['meta']['valid_from']),
53 validTo: Carbon::parse($item['checks']['certificate_health']['meta']['valid_to']),
54 ),
55 ),
56 ),
57 );
58 }
59}

As you can see from the above we are mapping everything that the API is responding with currently - for your integration you could choose the parts that are important to yourself and expand when needed.

Let's create our Monitor DTO under app/Services/PingPing/DTO/Monitor.php which should look like this:

1namespace App\Services\PingPing\DTO;
2 
3use Spatie\DataTransferObject\DataTransferObject;
4 
5class Monitor extends DataTransferObject
6{
7 public int $id;
8 public string $identifier;
9 public string $alias;
10 public string $scheme;
11 public string $host;
12 public string $port;
13 public string $url;
14 public string $statusPage;
15 public Checks $checks;
16}

As you can see in this DTO, we are pulling in a different DTO to handle the checks on a monitor, create this under app/Services/PingPing/DTO/Checks.php and it should look like the following:

1namespace App\Services\PingPing\DTO;
2 
3use Spatie\DataTransferObject\DataTransferObject;
4 
5class Checks extends DataTransferObject
6{
7 public Uptime $uptime;
8 public CertificateHealth $certificateHealth;
9}

Again as before, we have 2 further DTOs created here that we need to create under the same namespace:

1namespace App\Services\PingPing\DTO;
2 
3class Uptime extends Check
4{
5 public UptimeMeta $meta;
6}
1namespace App\Services\PingPing\DTO;
2 
3class CertificateHealth extends Check
4{
5 public CertificateHealthMeta $meta;
6}

What you will notice about these two, is that they are extending a completely different class instead of the usual DataTransferObject from Spatie. This is because both have identical fields except their meta information. The Check DTO looks like this:

1namespace App\Services\PingPing\DTO;
2 
3use Carbon\Carbon;
4use Spatie\DataTransferObject\DataTransferObject;
5 
6class Check extends DataTransferObject
7{
8 public int $id;
9 public string $status;
10 public null|string $error;
11 public int $interval;
12 public bool $enabled;
13 public int $notificationThreshold;
14 public Carbon $lastCheckAt;
15}

Now let us create the UptimeMeta DTO:

1namespace App\Services\PingPing\DTO;
2 
3use Carbon\Carbon;
4use Spatie\DataTransferObject\DataTransferObject;
5 
6class UptimeMeta extends DataTransferObject
7{
8 public int $httpStatusCode;
9 public int $averageUptimePercentage;
10 public int $averageResponseTime;
11 public null|Carbon $offlineSince;
12}

And now for the CertificateHealthMeta DTO:

1namespace App\Services\PingPing\DTO;
2 
3use Carbon\Carbon;
4use Spatie\DataTransferObject\DataTransferObject;
5 
6class CertificateHealthMeta extends DataTransferObject
7{
8 public string $issuer;
9 public string $signatureAlgorithm;
10 public bool $selfSigned;
11 public null|Carbon $validFrom;
12 public null|Carbon $validTo;
13}

So now we are mapping all of the response to DTOs using our CreateMonitor Action, we just need to create a MonitorCollection under app/Services/PingPing/Collections/MonitorCollection.php which should look like this:

1namespace App\Services\PingPing\Collections;
2 
3use Illuminate\Support\Collection;
4 
5class MonitorCollection extends Collection
6{
7 //
8}

Pretty simple right? All we want to do really is extend the Illuminate standard Collection so it can be extended at a later date.

So we have created all of our DTOs, a Collection, an Action to handle the creation. Now we just need to update our Client itself to make over everything!

1namespace App\Services\PingPing;
2 
3use App\Services\Concerns\HasFake;
4use Illuminate\Support\Facades\Http;
5use App\Services\PingPing\Actions\CreateMonitor;
6use App\Services\PingPing\Collections\MonitorCollection;
7 
8class Client
9{
10 use HasFake;
11 
12 public function __construct(
13 protected string $uri,
14 protected string $token,
15 protected int $timeout = 10,
16 protected null|int $retryTimes = null,
17 protected null|int $retryMilliseconds = null,
18 ) {}
19 
20 public function monitors()
21 {
22 $request = Http::withToken(
23 token: $this->token,
24 )->withHeaders([
25 'Accept' => 'application/json',
26 ])->timeout(
27 seconds: $this->timeout,
28 );
29 
30 if (
31 ! is_null($this->retryTimes)
32 && ! is_null($this->retryMilliseconds)
33 ) {
34 $request->retry(
35 times: $this->retryTimes,
36 sleep: $this->retryMilliseconds,
37 );
38 }
39 
40 $response = $request->get(
41 url: "{$this->uri}/monitors",
42 );
43 
44 if (! $response->successful()) {
45 return $response->toException();
46 }
47 
48 $collection = new MonitorCollection();
49 
50 foreach ($response->collect('data') as $item) {
51 $monitor = CreateMonitor::handle(
52 item: $item,
53 );
54 
55 $collection->add(
56 item: $monitor,
57 );
58 }
59 
60 return $collection;
61 }
62}

As you can see, we get the response from our API. Then if it wasn't successful we return the response as an exception, then we create our collection - map over the data in our response as a collection. Use our Action to create a full DTO and push this onto our collection, which we finally return.

The result of all of the above is a simple to use, and easy to extend API integration, which returns specific Objects - which you later extend to make requests yourself. During my time writing this article I was writing the code as I went along and testing in TinkerwellApp which I have found to be super useful for this sort of work. Below is a screenshot of the final working code and output:

Tinkerwell Output

If you enjoyed this article, why not let me know on twitter @JustSteveKing or checkout the repo for this tutorial on GitHub