forked from apoloz/alfa-bank-sdk
doc(base): libs docs added
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
# 🔁 Caching Responses
|
||||
|
||||
There are scenarios where you may want to cache a response from an API, like retrieving a static list or retrieving data that you know won't change for a specified amount of time. Caching can be incredibly powerful and can speed up an application by relying less on a third-party integration. Saloon has a [first-party plugin](https://github.com/Sammyjo20/saloon-cache-plugin) that you can install to enable caching support.
|
||||
|
||||
### Installation
|
||||
|
||||
To install the caching functionality into Saloon, install the plugin using Composer.
|
||||
|
||||
```bash
|
||||
composer require saloonphp/cache-plugin "^3.0"
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
Next, add the `Cacheable` interface and `HasCaching` trait to your request or connector. You must define the two methods.
|
||||
|
||||
* resolveCacheDriver
|
||||
* cacheExpiryInSeconds
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\CachePlugin\Contracts\Driver;
|
||||
use Saloon\CachePlugin\Traits\HasCaching;
|
||||
use Saloon\CachePlugin\Contracts\Cacheable;
|
||||
|
||||
class GetServersRequest extends Request implements Cacheable
|
||||
{
|
||||
use HasCaching;
|
||||
|
||||
// ...
|
||||
|
||||
public function resolveCacheDriver(): Driver
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
public function cacheExpiryInSeconds(): int
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% hint style="warning" %}
|
||||
When you add the `HasCaching` trait onto your connector, every request through the connector will be cached.
|
||||
{% endhint %}
|
||||
|
||||
### Cache Drivers
|
||||
|
||||
Saloon's caching plugin works with different caching drivers that you can use on your request or connector. The plugin comes with the following cache drivers:
|
||||
|
||||
* PsrCacheDriver (Supports PSR-16 Cache Implementations)
|
||||
* FlysystemDriver (Requires `league/flysystem` version 3)
|
||||
* LaravelCacheDriver (Supports any of Laravel's cache disks, requires Laravel)
|
||||
|
||||
{% tabs %}
|
||||
{% tab title="PsrCacheDriver" %}
|
||||
```php
|
||||
use Saloon\CachePlugin\Drivers\PsrCacheDriver;
|
||||
|
||||
public function resolveCacheDriver(): Driver
|
||||
{
|
||||
// This example uses the PhpArrayAdapter from
|
||||
// the symfony/cache library.
|
||||
|
||||
return new PsrCacheDriver(new PhpArrayAdapter);
|
||||
}
|
||||
```
|
||||
{% endtab %}
|
||||
|
||||
{% tab title="FlysystemDriver" %}
|
||||
```php
|
||||
use Saloon\CachePlugin\Drivers\FlysystemDriver;
|
||||
|
||||
public function resolveCacheDriver(): Driver
|
||||
{
|
||||
// This example uses the "AwsS3V3Adapter" driver
|
||||
// that is provided by Flysystem.
|
||||
|
||||
return new FlysystemDriver(
|
||||
new Filesystem(new AwsS3V3Adapter($s3Client, 'bucket-name'))
|
||||
);
|
||||
}
|
||||
```
|
||||
{% endtab %}
|
||||
|
||||
{% tab title="LaravelCacheDriver" %}
|
||||
```php
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Saloon\CachePlugin\Drivers\LaravelCacheDriver;
|
||||
|
||||
public function resolveCacheDriver(): Driver
|
||||
{
|
||||
// This example uses Redis cache store that
|
||||
// Laravel provides.
|
||||
|
||||
return new LaravelCacheDriver(Cache::store('redis'));
|
||||
}
|
||||
```
|
||||
{% endtab %}
|
||||
{% endtabs %}
|
||||
|
||||
### Expiry
|
||||
|
||||
When Saloon caches a request, it will last a specified amount of time in seconds. You should specify this time in the `cacheExpiryInSeconds` method.
|
||||
|
||||
```php
|
||||
public function cacheExpiryInSeconds(): int
|
||||
{
|
||||
return 3600; // One Hour
|
||||
}
|
||||
```
|
||||
|
||||
### Caching Requests
|
||||
|
||||
Once you have configured the cache driver and expiry, Saloon will automatically cache requests and store them in your requested cache-store. The next time you send a request, the cached response will be automatically swapped out and no real request will be sent.
|
||||
|
||||
#### Checking if a response is cached
|
||||
|
||||
You may use the `isCached()` method to determine if a response is cached.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
$forge = new ForgeConnector;
|
||||
|
||||
$response = $forge->send(new GetServersRequest);
|
||||
$response->isCached(); // false
|
||||
|
||||
// Next time it is sent...
|
||||
|
||||
$response = $forge->send(new GetServersRequest);
|
||||
$response->isCached(); // true
|
||||
```
|
||||
|
||||
#### When will Saloon cache a request?
|
||||
|
||||
Saloon will only cache a **successful** request when the method is either GET or OPTIONS. You can customise this by extending the `getCacheableMethods` method where you added the `HasCaching` trait.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\Enums\Method;
|
||||
|
||||
class GetServersRequest extends Request implements Cacheable
|
||||
{
|
||||
use HasCaching;
|
||||
|
||||
protected function getCacheableMethods(): array
|
||||
{
|
||||
return [Method::GET, Method::OPTIONS, Method::POST];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You may customise when Saloon considers a request as successful. To read more about this, [click here.](../the-basics/handling-failures.md#customising-when-saloon-thinks-a-request-has-failed)
|
||||
|
||||
### Customising the cache key
|
||||
|
||||
By default, the cache key is created from the full request URL, the headers that are sent and the query parameters that are used. You may choose to define your own custom cache key. Just extend the protected `cacheKey` method where you added the `HasCaching` trait. You will get access to the `PendingRequest` instance that contains all the request properties.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\Http\PendingRequest;
|
||||
|
||||
class GetServersRequest extends Request implements Cacheable
|
||||
{
|
||||
use HasCaching;
|
||||
|
||||
protected function cacheKey(PendingRequest $pendingRequest): ?string
|
||||
{
|
||||
return 'custom-cache-key';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Invalidating the current cache
|
||||
|
||||
You may want to make a request and purge the existing cache before making the request. You can use the `invalidateCache` method on the request before sending the request and Saloon will delete any existing cache for that request.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
$forge = new ForgeConnector;
|
||||
|
||||
$request = new GetServersRequest;
|
||||
$request->invalidateCache();
|
||||
|
||||
$response = $forge->send($request);
|
||||
```
|
||||
|
||||
### Temporarily Disabling Caching
|
||||
|
||||
Sometimes you may wish to disable the caching on a per-request basis for debugging or to bypass caching. You can do this by using the `disableCaching` method on the request.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
$forge = new ForgeConnector;
|
||||
|
||||
$request = new GetServersRequest;
|
||||
$request->disableCaching();
|
||||
|
||||
$response = $forge->send($request);
|
||||
```
|
||||
|
||||
### Source Code
|
||||
|
||||
To view the source code of this plugin, [click here](https://github.com/Sammyjo20/saloon-cache-plugin).
|
||||
@@ -0,0 +1,495 @@
|
||||
# ⛔ Rate Limit Handler
|
||||
|
||||
Handling rate limits with API integrations can be hard. Saloon has a first-party plugin that provides you with the tools you need to prevent rate limits and handle what happens if a rate limit is exceeded.
|
||||
|
||||
With this plugin, you are able to define various limits on a per-connector or request basis. You can also control if Saloon should throw an exception or sleep if a limit is reached. Saloon will keep track of how many requests are made and when a rate limit is hit, Saloon will prevent further requests on the connector/request until the rate limit has been lifted.
|
||||
|
||||
Saloon will even listen out for "429 Too Many Requests" responses and will automatically throw exceptions before your future requests are sent and the limit will be lifted based on the `Retry-After` header.
|
||||
|
||||
This plugin also comes with a Laravel Job middleware which you can use inside of your jobs to automatically release them back onto the queue if a rate limit has been reached.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
use Saloon\Traits\Plugins\AcceptsJson;
|
||||
use Saloon\RateLimitPlugin\Stores\RedisStore;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use AcceptsJson;
|
||||
use HasRateLimits;
|
||||
|
||||
public function resolveBaseUrl(): string
|
||||
{
|
||||
return 'https://api.spotify.com/v1';
|
||||
}
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(100)->everyMinute(),
|
||||
Limit::allow(1000)->everyDay(),
|
||||
Limit::allow(5000)->everyMonth(),
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
$redis = new Redis;
|
||||
$redis->connect('127.0.0.1');
|
||||
|
||||
return new RedisStore($redis);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Installation
|
||||
|
||||
You can install this plugin via Composer.
|
||||
|
||||
```
|
||||
composer require saloonphp/rate-limit-plugin "^2.0"
|
||||
```
|
||||
|
||||
### Getting Started
|
||||
|
||||
To use the plugin, add the `HasRateLimit` trait to your connector or request. If you have a connector, you should put it on the connector, but it can be put on an individual request if a specific endpoint has a different rate limit or if you are using solo requests. If you are using the trait on both your connector and request, the rate limits are combined together.
|
||||
|
||||
```php
|
||||
use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use HasRateLimits;
|
||||
}
|
||||
```
|
||||
|
||||
Next, you will be required to implement two methods: `resolveLimits` and `resolveRateLimitStore`. These methods allow you to define the limits that Saloon will keep track of and the store where the limit "hits" will be kept.
|
||||
|
||||
```php
|
||||
use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\MemoryStore;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use HasRateLimits;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
return new MemoryStore;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Stores
|
||||
|
||||
Here are the various stores that the rate-limiting plugin supports. You may also [create your own stores](https://github.com/Sammyjo20/saloon-docs/blob/v2/digging-deeper/broken-reference/README.md) if this library does not come with the one you need. Stores are used to keep track of how many requests have been sent through a given connector/request.
|
||||
|
||||
#### Available Stores
|
||||
|
||||
* In-Memory (Array)
|
||||
* File
|
||||
* Redis
|
||||
* Predis
|
||||
* PSR Cache Store
|
||||
* Laravel Cache Store
|
||||
|
||||
#### Memory Store
|
||||
|
||||
The simplest store. This store is persisted on the current instance of the connector/request and all information is lost when the connector is destructed.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\MemoryStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
return new MemoryStore;
|
||||
}
|
||||
```
|
||||
|
||||
#### File Store
|
||||
|
||||
This store will use the local filesystem to store the limits. The only requirement for this store is for you to define the absolute path to a directory where you would like the limits to be stored.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\FileStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
return new FileStore('some/application/directory');
|
||||
}
|
||||
```
|
||||
|
||||
#### Redis Store
|
||||
|
||||
This store will use PHP's `Redis` extension to store the limits on a Redis database. You should pass the Redis configuration into this store.
|
||||
|
||||
```php
|
||||
use Redis;
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\RedisStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
$client = new Redis;
|
||||
$client->connect('127.0.0.1');
|
||||
|
||||
return new RedisStore($client);
|
||||
}
|
||||
```
|
||||
|
||||
#### Predis Store
|
||||
|
||||
Similar to the `RedisStore`, the `PredisStore` allows you to connect to Redis through the `predis/predis` PHP library.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\PredisStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
$client = new Predis\Client([
|
||||
'scheme' => 'tcp',
|
||||
'host' => '10.0.0.1',
|
||||
'port' => 6379,
|
||||
]);
|
||||
|
||||
return new PredisStore($client);
|
||||
}
|
||||
```
|
||||
|
||||
#### PSR Cache Store
|
||||
|
||||
This store supports any PSR-16 cache store provided by the `psr/simple-cache` library.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\PsrStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
return new PsrStore(new SomePsr16Store);
|
||||
}
|
||||
```
|
||||
|
||||
#### Laravel Cache Store
|
||||
|
||||
This store can only be used in a Laravel environment but allows you to use any of Laravel's cache disks.
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
use Saloon\RateLimitPlugin\Stores\LaravelCacheStore;
|
||||
|
||||
protected function resolveRateLimitStore(): RateLimitStore
|
||||
{
|
||||
return new LaravelCacheStore(Cache::store('redis'));
|
||||
}
|
||||
```
|
||||
|
||||
### Limits
|
||||
|
||||
While this plugin can detect if a 429 status occurs from a response, it's better to prevent your application from hitting rate limits than let them happen. This plugin provides an expressive `Limit` class which can be used to define different limits. You can define as many limits as you like, with various intervals.
|
||||
|
||||
#### What limit type should I be using?
|
||||
|
||||
The rate limit plugin supports two types of limits, time-based limiters, for example 100 requests every 60 seconds and a "Leaky Bucket" limiter. Please continue reading if you need to use time-based limiters or you can [click here for leaky bucket limiters](handling-rate-limits.md#leaky-bucket-limiter).
|
||||
|
||||
#### Configuring Limits
|
||||
|
||||
Here is a simple example of a limit for an API which only allows 60 requests per minute, but has a daily limit of 1,000 API calls. There are many different limit intervals, as well as different ways you can instruct Saloon to handle the limit. There is no restriction on the number of limits you can have.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(60)->everyMinute(),
|
||||
Limit::allow(1000)->everyDay(),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
#### Limit Intervals
|
||||
|
||||
There are various limit intervals which you can use on your limiter, ranging for seconds to up to the end of the month.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
|
||||
Limit::allow(60)->everySeconds(seconds: 5);
|
||||
Limit::allow(60)->everyMinute();
|
||||
Limit::allow(60)->untilEndOfMinute();
|
||||
Limit::allow(60)->everyFiveMinutes();
|
||||
Limit::allow(60)->everyThirtyMinutes();
|
||||
Limit::allow(60)->everyHour();
|
||||
Limit::allow(60)->untilEndOfHour();
|
||||
Limit::allow(60)->everySixHours();
|
||||
Limit::allow(60)->everyTwelveHours();
|
||||
Limit::allow(60)->everyDay();
|
||||
Limit::allow(60)->everyDayUntil('8pm');
|
||||
Limit::allow(60)->untilMidnightTonight();
|
||||
Limit::allow(60)->untilEndOfMonth();
|
||||
```
|
||||
|
||||
#### Custom Names
|
||||
|
||||
Sometimes you may need to add a name to your limiter. A good example of this is if you have separate API keys per user and therefore require a different API rate limit per user. You can add the `name()` method to your limit to specify a custom name for your limiter. Each limiter's name must be unique.
|
||||
|
||||
```php
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(60)->everyMinute()->name('spotify-limit-user-' . $this->userId),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
#### Custom Prefixes
|
||||
|
||||
Saloon will append the class name of the connector or a request as the prefix to the limiter name. For example SpotifyConnector:30\_every\_60. You may customise the prefix by extending the `getLimiterPrefix` method on your connector or request.
|
||||
|
||||
```php
|
||||
protected function getLimiterPrefix(): ?string
|
||||
{
|
||||
return 'spotify-user-' . $this->userId;
|
||||
}
|
||||
```
|
||||
|
||||
#### Custom Thresholds
|
||||
|
||||
You may want to specify the percentage threshold that Saloon should accept as the number of "hits" on a given limit. This is useful if you want to stay just under the real API limit while still defining the limit in the connector/request.
|
||||
|
||||
The threshold must be a number between 0 and 1 (e.g 0.8 = 80%)
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(60, threshold: 0.8)->everyMinute(), // Will fail when at 80% capacity
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
#### Sleep
|
||||
|
||||
If would rather Saloon didn't throw an exception, you can use the `sleep` method when defining a limit. When using the sleep method, an exception won't be thrown. Instead, Saloon will wait the remaining number of seconds before a request is attempted again.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(60)->sleep(),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
#### "429: Too Many Attempts" Detection
|
||||
|
||||
While it's recommended that you should define your limits above, Saloon will try to catch 429 "Too Many Attempts" errors from an API and will automatically mark a limit as "exceeded" if it sees this status. By default, Saloon will attempt to parse the `Retry-After` header to work out when a limit has been exceeded. If Saloon cannot calculate this, the limit will be released after 60 seconds.
|
||||
|
||||
You can customise this behaviour by overwriting the `handleTooManyAttempts` method.
|
||||
|
||||
```php
|
||||
protected function handleTooManyAttempts(Response $response, Limit $limit): void
|
||||
{
|
||||
if ($response->status() !== 429) {
|
||||
return;
|
||||
}
|
||||
|
||||
$limit->exceeded(
|
||||
releaseInSeconds: RetryAfterHelper::parse($response->header('Retry-After')),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you may choose to disable this functionality. You can do this by setting the `detectTooManyAttempts` property to `false` in your connector/request's constructor.
|
||||
|
||||
<pre class="language-php"><code class="lang-php">use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Stores\MemoryStore;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use HasRateLimits;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
<strong> $this->detectTooManyAttempts = false;
|
||||
</strong> }
|
||||
}
|
||||
</code></pre>
|
||||
|
||||
When Saloon detects a rate limit has been exceeded, Saloon will throw a `RateLimitReachedException` . If you would like your application to sleep instead of throwing an exception you can extend the `getTooManyAttemptsLimiter` method and apply the `sleep` modifier
|
||||
|
||||
<pre class="language-php"><code class="lang-php">use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Stores\MemoryStore;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use HasRateLimits;
|
||||
|
||||
protected function getTooManyAttemptsLimiter(): ?Limit
|
||||
{
|
||||
<strong> return Limit::custom($this->handleTooManyAttempts(...))->sleep();
|
||||
</strong> }
|
||||
}
|
||||
</code></pre>
|
||||
|
||||
{% hint style="warning" %}
|
||||
When using the `sleep` modifier, Saloon will automatically attempt to make another request after detecting a rate limit being reached in the response. This does not affect the retry definition you may have defined on your connector or request.
|
||||
{% endhint %}
|
||||
|
||||
### Leaky Bucket Limiter
|
||||
|
||||
Some applications may implement a "Leaky Bucket" algorithm for their rate limits, essentially this means that while you are making requests, within a given time frame (usually every second) you "gain" additional requests you can make. For example if an API integration allowed 60 requests per minute but had a leak rate of 1 per second, you could in theory be constantly communicating with the API as long as you stay within the 60 request limit.
|
||||
|
||||
The plugin implementation is really straight forward. In order to implement the above example you would write something like this.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Bucket;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Bucket::capacity(60)
|
||||
->leak(1)
|
||||
->everySeconds(1)
|
||||
->sleep()
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
{% hint style="info" %}
|
||||
The `Bucket` class extends the `Limit` class so you may use all of the limit intervals as defined above.
|
||||
{% endhint %}
|
||||
|
||||
You'll notice that it does an initial burst of 60 requests, then the bucket fills back up and the next second does 1 request, then the next second does 1 request, which adheres to our "leak 1 every 1 second" specification.
|
||||
|
||||
### Handling Rate Limits Being Exceeded
|
||||
|
||||
When a rate limit has been reached, Saloon will throw a `RateLimitReachedException`. This exception contains a `getLimit` method which may be used to see the limit that has thrown the exception and see the number of seconds to wait before a request can be sent again. This can be done with a simple try-catch approach or if you are using the provided Laravel job middleware, then you can instruct your jobs to wait until the limit has been lifted.
|
||||
|
||||
#### Try/Catch
|
||||
|
||||
As mentioned above, Saloon will throw an exception if a rate limit is reached or if the API returns a 429: Too Many Requests response. You could use a try/catch block to catch the exception and do something with the limit. For example, you may return an error to your users to let them know how long they need to wait - or you might retry the request later. If you are using Saloon in a context of a queued process, then you may want to retry the queued job in the future, from the remaining seconds.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Exceptions\RateLimitReachedException;
|
||||
|
||||
$spotify = new SpotifyConnector;
|
||||
|
||||
try {
|
||||
$response = $spotify->send(new GetPlaylistRequest);
|
||||
} catch (RateLimitReachedException $exception) {
|
||||
$seconds = $exception->getLimit()->getRemainingSeconds();
|
||||
|
||||
// Return our users back to our application with a custom response that could be
|
||||
// shown on the front end.
|
||||
|
||||
return response("Too many requests to Spotify's API. Please try again in ${$seconds} seconds.");
|
||||
}
|
||||
```
|
||||
|
||||
#### Sleep
|
||||
|
||||
If would rather Saloon didn't throw an exception, you can use the `sleep` method when defining a limit. When using the sleep method, an exception won't be thrown. Instead, Saloon will wait the remaining number of seconds before a request is attempted again.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Limit;
|
||||
|
||||
protected function resolveLimits(): array
|
||||
{
|
||||
return [
|
||||
Limit::allow(60)->sleep(),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
#### Laravel Job Middleware
|
||||
|
||||
If you are using Laravel, then this library comes with a [job middleware](https://laravel.com/docs/queues#job-middleware) that you can use. This job middleware will catch the `RateLimitReachedException` and automatically release your job back onto the queue with the remaining seconds added. Add this to the `middleware` method on your Laravel Job.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Helpers\ApiRateLimited;
|
||||
|
||||
public function middleware(): array
|
||||
{
|
||||
return [new ApiRateLimited];
|
||||
}
|
||||
```
|
||||
|
||||
{% hint style="info" %}
|
||||
You may also wish to increase your job's tries when using this middleware in case the job needs to be retried multiple times.
|
||||
{% endhint %}
|
||||
|
||||
### Creating your own store
|
||||
|
||||
You may create your own rate limit store by implementing the `RateLimitStore` interface.
|
||||
|
||||
```php
|
||||
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
|
||||
|
||||
class CustomStore implements RateLimitStore
|
||||
{
|
||||
/**
|
||||
* Get a rate limit from the store
|
||||
*/
|
||||
public function get(string $key): ?string
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the rate limit in the store
|
||||
*/
|
||||
public function set(string $key, string $value, int $ttl): bool
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Disabling Rate Limiting
|
||||
|
||||
Sometimes you might want to disable rate limiting by default or even disable it on a per-connector basis. You can either use a property to disable the rate-limiting functionality by default, or you can use the `useRateLimitPlugin()` method to disable it on a per-instance basis.
|
||||
|
||||
<pre class="language-php"><code class="lang-php">use Saloon\Http\Connector;
|
||||
use Saloon\RateLimitPlugin\Traits\HasRateLimits;
|
||||
|
||||
class SpotifyConnector extends Connector
|
||||
{
|
||||
use HasRateLimits;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
<strong> $this->rateLimitingEnabled = false;
|
||||
</strong> }
|
||||
}
|
||||
|
||||
// Or...
|
||||
|
||||
$connector = new SpotifyConnector;
|
||||
$connector->useRateLimitPlugin(false);
|
||||
</code></pre>
|
||||
@@ -0,0 +1,69 @@
|
||||
# ⛵ Laravel Plugin
|
||||
|
||||
Saloon has been built to integrate beautifully with [Laravel](https://laravel.com). The separate Laravel plugin comes with a facade that helps with mocking and recording requests, Artisan console commands to easily build your API integrations, and events which you can listen to and build further functionality from.
|
||||
|
||||
### Installation
|
||||
|
||||
You can install the separate package with Composer. You must already have`saloonphp/saloon` as a required dependency in your `composer.json` file.
|
||||
|
||||
```bash
|
||||
composer require saloonphp/laravel-plugin "^3.0"
|
||||
```
|
||||
|
||||
Next, publish the configuration file with the following Artisan command
|
||||
|
||||
```bash
|
||||
php artisan vendor:publish --tag=saloon-config
|
||||
```
|
||||
|
||||
### Artisan Console Commands
|
||||
|
||||
The Laravel plugin provides a few useful Artisan commands that can help you build your API integrations.
|
||||
|
||||
<table><thead><tr><th width="364">Command</th><th>Description</th></tr></thead><tbody><tr><td>php artisan saloon:connector</td><td>Creates a new connector - You can provide an optional <code>--oauth</code> option if you would like to create an OAuth2 connector.</td></tr><tr><td>php artisan saloon:request</td><td>Creates a new request</td></tr><tr><td>php artisan saloon:response</td><td>Creates a custom response</td></tr><tr><td>php artisan saloon:plugin</td><td>Creates a plugin</td></tr><tr><td>php artisan saloon:auth</td><td>Creates a custom authenticator</td></tr><tr><td>php artisan saloon:list</td><td>List all your API integrations</td></tr></tbody></table>
|
||||
|
||||
### Saloon Facade
|
||||
|
||||
The Laravel plugin also provides a facade which can be used to feel more unified with the rest of Laravel. You can use the Facade in tests instead of the `MockClient::global()` method.
|
||||
|
||||
```php
|
||||
use Saloon\Laravel\Facades\Saloon;
|
||||
|
||||
Saloon::fake([
|
||||
GetServersRequest::class => MockResponse::make(body: '', status: 200),
|
||||
]);
|
||||
```
|
||||
|
||||
To learn more about testing API integrations, [click here](../the-basics/testing/).
|
||||
|
||||
### Laravel Nightwatch Support
|
||||
|
||||
From v3.6.0 the Saloon Laravel plugin natively supports Laravel Nightwatch. The plugin will automatically register a Nightwatch middleware on all of your connectors.
|
||||
|
||||
### Laravel Telescope Support
|
||||
|
||||
From v3.8.0 the Saloon Laravel plugin natively supports Laravel Telescope. The plugin will automatically register a Telescope middleware on all of your connectors.
|
||||
|
||||
### Events
|
||||
|
||||
With the Laravel plugin installed, Saloon will start sending events when requests are being sent. These events are:
|
||||
|
||||
* SendingSaloonRequest
|
||||
* SentSaloonRequest
|
||||
|
||||
These events can be added to your `EventServiceProvider` and you can create listeners to handle when these happen.
|
||||
|
||||
### Laravel Zero
|
||||
|
||||
If you are using [Laravel Zero](https://github.com/laravel-zero/laravel-zero), the `SaloonServiceProvider` that registers the `Saloon` facade as well as some default middleware might not be registered. You can register Saloon's service provider in your `AppServiceProvider.php`'s `register()` method definition.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\Laravel\SaloonServiceProvider;
|
||||
|
||||
public function register()
|
||||
{
|
||||
$this->app->register(SaloonServiceProvider::class);
|
||||
}
|
||||
```
|
||||
178
_docs/laravel-libs/saloon-docs/installable-plugins/lawman.md
Normal file
178
_docs/laravel-libs/saloon-docs/installable-plugins/lawman.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# 🤠 Lawman
|
||||
|
||||
Lawman is a [PestPHP](https://pestphp.com/) Plugin for SaloonPHP which allows you to easily write architecture tests for your API integrations with a focus on them being easy to write and easy to read. After all, if SaloonPHP makes our API integrations beautiful, the tests for them should be beautiful too, right?
|
||||
|
||||
Lawman is a third-party plugin written and maintained by [Jon Purvis](https://twitter.com/JonPurvis\_) and gives you access to Expectations for your Connectors, Requests, Plugins and more, to ensure they stick to whichever architecture rules your application has.
|
||||
|
||||
One of the great things about Lawman is because it's a Pest plugin, it will work with regular PestPHP Expectations, just chain them up and you're good to go!
|
||||
|
||||
### Installation
|
||||
|
||||
You can install the plugin using Composer. If you run the following command, it will install it as a dev dependency:
|
||||
|
||||
```bash
|
||||
composer require jonpurvis/lawman --dev
|
||||
```
|
||||
|
||||
Lawman makes use of autoloading with Composer, so once you've installed the package, the Expectations should appear as you type!
|
||||
|
||||
### Examples
|
||||
|
||||
Let's take a look at how you can use Lawman to easily write Arch tests for your API Integrations.
|
||||
|
||||
Let's say we have a Connector class that we want to test, with PestPHP we could do the following:
|
||||
|
||||
```php
|
||||
test('connector')
|
||||
->expect('App\Http\Integrations\Integration\Connector')
|
||||
->toExtend('Saloon\Http\Connector')
|
||||
->toUse('Saloon\Traits\Plugins\AcceptsJson')
|
||||
->toUse('Saloon\Traits\Plugins\AlwaysThrowOnErrors');
|
||||
```
|
||||
|
||||
So that test is ensuring our class extends the base Connector and uses the `AcceptJson` and `AlwaysThrowOnErrors` traits. Whilst that test works, we could perhaps make it quicker to write and easier to read, so with Lawman, you can do:
|
||||
|
||||
```php
|
||||
test('connector')
|
||||
->expect('App\Http\Integrations\Integration\Connector')
|
||||
->toBeSaloonConnector()
|
||||
->toUseAcceptsJsonTrait()
|
||||
->toUseAlwaysThrowOnErrorsTrait();
|
||||
```
|
||||
|
||||
Next up, let's take a Request test that we have:
|
||||
|
||||
```php
|
||||
test('request')
|
||||
->expect('App\Http\Integrations\Integration\Requests\Request')
|
||||
->toExtend('\Saloon\Http\Request')
|
||||
->toImplement('Saloon\Contracts\Body\HasBody')
|
||||
->toUse('Saloon\Traits\Body\HasFormBody')
|
||||
->toUse('Saloon\Traits\Plugins\AcceptsJson');
|
||||
```
|
||||
|
||||
Lawman makes this test much nicer to read:
|
||||
|
||||
```php
|
||||
test('request')
|
||||
->expect('App\Http\Integrations\Integration\Requests\Request')
|
||||
->toBeSaloonRequest()
|
||||
->toSendPostRequest()
|
||||
->toHaveFormBody()
|
||||
->toUseAcceptsJsonTrait();
|
||||
```
|
||||
|
||||
What about if we want to test our Connector has an Authentication method? Lawman makes this easy to do, it even works with multi auth:
|
||||
|
||||
```php
|
||||
test('connector')
|
||||
->expect('App\Http\Integrations\Integration\Connector')
|
||||
->toBeSaloonConnector()
|
||||
->toUseCertificateAuthentication()
|
||||
->toUseTokenAuthentication();
|
||||
```
|
||||
|
||||
Lawman also has Expectations for the Pagination, Cache and Rate Limit Plugins:
|
||||
|
||||
```php
|
||||
test('request')
|
||||
->expect('App\Http\Integrations\Integration\Requests\Request')
|
||||
->toBeSaloonRequest()
|
||||
->toSendPostRequest()
|
||||
->toUsePagedPagination()
|
||||
->toHaveCaching()
|
||||
->toHaveRateLimits()
|
||||
```
|
||||
|
||||
Maybe our Connector has some Retry instructions that we want to test. Again, with Lawman, it's as simple as:
|
||||
|
||||
```php
|
||||
test('connector')
|
||||
->expect('App\Http\Integrations\Integration\Connector')
|
||||
->toBeSaloonConnector()
|
||||
->toBeTriedAgainOnFailure()
|
||||
->toHaveRetryInterval()
|
||||
->toUseExponentialBackoff()
|
||||
```
|
||||
|
||||
### Available Expectations
|
||||
|
||||
#### Authentication
|
||||
|
||||
* `toUseTokenAuthentication`
|
||||
* `toUseBasicAuthentication`
|
||||
* `toUseCertificateAuthentication`
|
||||
* `toUseHeaderAuthentication`
|
||||
|
||||
#### Cache
|
||||
|
||||
* `toHaveCaching`
|
||||
|
||||
#### Connector
|
||||
|
||||
* `toBeSaloonConnector`
|
||||
|
||||
#### Pagination
|
||||
|
||||
* `toUsePagedPagination`
|
||||
* `toUseOffsetPagination`
|
||||
* `toUseCursorPagination`
|
||||
* `toUseCustomPagination`
|
||||
|
||||
#### Properties
|
||||
|
||||
* `toSetConnectTimeout`
|
||||
* `toSetRequestTimeout`
|
||||
* `toBeTriedAgainOnFailure`
|
||||
* `toHaveRetryInterval`
|
||||
* `toUseExponentialBackoff`
|
||||
* `toThrowOnMaxTries`
|
||||
|
||||
#### Rate Limit
|
||||
|
||||
* `toHaveRateLimits`
|
||||
|
||||
#### Request
|
||||
|
||||
* `toBeSaloonRequest`
|
||||
* `toHaveRequestMethod`
|
||||
* `toSendGetRequest`
|
||||
* `toSendPostRequest`
|
||||
* `toSendHeadRequest`
|
||||
* `toSendPutRequest`
|
||||
* `toSendPatchRequest`
|
||||
* `toSendDeleteRequest`
|
||||
* `toSendOptionsRequest`
|
||||
* `toSendConnectRequest`
|
||||
* `toSendTraceRequest`
|
||||
* `toHaveJsonBody`
|
||||
* `toHaveMultipartBody`
|
||||
* `toHaveXmlBody`
|
||||
* `toHaveFormBody`
|
||||
* `toHaveStringBody`
|
||||
* `toHaveStreamBody`
|
||||
|
||||
#### Response
|
||||
|
||||
* `toBeSaloonResponse`
|
||||
|
||||
#### Trait
|
||||
|
||||
* `toUseAcceptsJsonTrait`
|
||||
* `toUseAlwaysThrowOnErrorsTrait`
|
||||
* `toUseTimeoutTrait`
|
||||
* `toUseAuthorisationCodeGrantTrait`
|
||||
* `toUseClientCredentialsGrantTrait`
|
||||
|
||||
### Contributing
|
||||
|
||||
Contributions to Lawman are welcome! If you can think of an Expectation that would be useful for others to utilise in their tests, please submit a PR on GitHub. The only real rules are:
|
||||
|
||||
* All Expectations must have a test to cover it
|
||||
* A new Fixture class should be added for every new Expectation
|
||||
|
||||
If you just follow how previous Expectations are done, then you should be good.
|
||||
|
||||
### Reporting an Issue
|
||||
|
||||
If you do spot an issue with Lawman, please [open an issue](https://github.com/JonPurvis/lawman/issues) on GitHub.
|
||||
@@ -0,0 +1,57 @@
|
||||
# 🏭 SDK Generator
|
||||
|
||||
The Saloon SDK Generator is a third-party Saloon plugin written and maintained by [Crescat](https://crescat.io/) ([Helge Sverre](https://twitter.com/HelgeSverre)) and allows people to easily generate Saloon SDKs from an OpenAPI file or Postman collection. The generator can automatically create connectors, requests and responses for you to help save you time when starting a new SDK. 
|
||||
|
||||
{% hint style="info" %}
|
||||
Note: This tool helps you set up the foundation for your SDK, but it might not create a complete, ready-to-use solution.
|
||||
{% endhint %}
|
||||
|
||||
<figure><img src="../.gitbook/assets/header (1).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Installation
|
||||
|
||||
You can install the Saloon SDK Generator through Composer. You can install it globally on your machine and have a simple CLI to generate SDKs.
|
||||
|
||||
```sh
|
||||
composer global require crescat-io/saloon-sdk-generator
|
||||
```
|
||||
|
||||
{% hint style="info" %}
|
||||
The library requires PHP 8.1 and above
|
||||
{% endhint %}
|
||||
|
||||
### Basic Usage
|
||||
|
||||
To generate the PHP SDK from an API specification file, run the following command:
|
||||
|
||||
```sh
|
||||
sdkgenerator generate:sdk API_SPEC_FILE.{json|yaml|yml}
|
||||
--type={postman|openapi}
|
||||
[--name=SDK_NAME]
|
||||
[--output=OUTPUT_PATH]
|
||||
[--namespace=Company\\Integration]
|
||||
[--force]
|
||||
[--dry]
|
||||
[--zip]
|
||||
```
|
||||
|
||||
Replace the placeholders with the appropriate values:
|
||||
|
||||
* `API_SPEC_FILE`: Path to the API specification file (JSON or YAML format).
|
||||
* `--type`: Specify the type of API specification (`postman` or `openapi`).
|
||||
* `--name`: (Optional) Specify the name of the generated SDK (default: Unnamed).
|
||||
* `--namespace`: (Optional) Specify the root namespace for the SDK (default: `App\\Sdk`).
|
||||
* `--output`: (Optional) Specify the output path where the generated code will be created (default: ./Generated).
|
||||
* `--force`: (Optional) Force overwriting existing files.
|
||||
* `--dry`: (Optional) Perform a dry run. It will not save generated files, only show a list of them.
|
||||
* `--zip`: (Optional) Use this flag to generate a zip archive containing all the generated files.
|
||||
|
||||
### Full Documentation
|
||||
|
||||
The full documentation can be found by visiting the Github repository here:
|
||||
|
||||
{% embed url="https://github.com/crescat-io/saloon-sdk-generator" %}
|
||||
|
||||
### Issue Tracking
|
||||
|
||||
As this is not directly affiliated with Saloon, please report any issues you have directly on the repository linked above.
|
||||
48
_docs/laravel-libs/saloon-docs/installable-plugins/traits.md
Normal file
48
_docs/laravel-libs/saloon-docs/installable-plugins/traits.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# 🏗 Building Your Own Plugins
|
||||
|
||||
Saloon has plugins which make it easy for you to add logic to your connector or requests in a reusable and elegant way. Plugins are traits that can be added to either a request or a connector and have a special "boot" method which is invoked during the request lifecycle.
|
||||
|
||||
### Getting Started
|
||||
|
||||
It's easy to create your own plugin for Saloon, just create a trait and add it to either your connector or request. In this example, we will create a logging plugin that when added will log the request being sent to [Ray](https://myray.app/).
|
||||
|
||||
Our plugin will be called `HasLogging` . In order for Saloon to execute this plugin, we must create a public method that starts with `boot` followed by the name of the trait. For example: `bootHasLogging`. The method is given an instance of `PendingRequest`.
|
||||
|
||||
{% tabs %}
|
||||
{% tab title="Definition (Trait)" %}
|
||||
<pre class="language-php"><code class="lang-php"><?php
|
||||
|
||||
trait HasLogging
|
||||
{
|
||||
<strong> public function bootHasLogging(PendingRequest $pendingRequest): void
|
||||
</strong> {
|
||||
ray($pendingRequest);
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
|
||||
{% hint style="warning" %}
|
||||
You must not use `$this` inside of the trait, as mutating the original request or connector is discouraged. The PendingRequest is the source of truth while a request is being sent.
|
||||
{% endhint %}
|
||||
{% endtab %}
|
||||
|
||||
{% tab title="Usage (Connector)" %}
|
||||
<pre class="language-php"><code class="lang-php"><?php
|
||||
|
||||
class ForgeConnector extends Connector
|
||||
{
|
||||
<strong> use HasLogging;
|
||||
</strong>}
|
||||
</code></pre>
|
||||
{% endtab %}
|
||||
{% endtabs %}
|
||||
|
||||
When you send your request, plugins are the first things that are invoked, even before the `boot` method. This is to allow maximum compatibility with [middleware ](../digging-deeper/middleware.md)and [authenticators](../the-basics/authentication.md). This also means that because it's the first process in the chain, other steps like middleware and the boot method will be able to overwrite anything added by a plugin.
|
||||
|
||||
<figure><img src="../.gitbook/assets/Saloon v2 (1).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Because we added the trait to our connector, every request will use the `HasLogging` plugin. If you would like the plugin to be applied to just one request, you can add the plugin to the request only. 
|
||||
|
||||
{% hint style="warning" %}
|
||||
Take caution when adding the plugin to both the connector and the request, because the plugin will be executed twice.
|
||||
{% endhint %}
|
||||
@@ -0,0 +1,121 @@
|
||||
# 🏇 XML Wrangler
|
||||
|
||||
XML Wrangler is a first-party library written by the maintainer of Saloon and is designed to modernise reading and writing XML in PHP. XML Wrangler can detect errors in XML, read gigabytes of XML files and convert XML results into Laravel Collections. Its powerful reader supports dot notation and XPath queries.
|
||||
|
||||
### Key Features
|
||||
|
||||
* Convert XML into an array
|
||||
* Write XML from an array
|
||||
* Memory-safe reader for large XML documents
|
||||
* Dot notation and XPath support for reading
|
||||
|
||||
{% tabs %}
|
||||
{% tab title="Reader" %}
|
||||
```php
|
||||
use Saloon\XmlWrangler\XmlReader;
|
||||
|
||||
$reader = XmlReader::fromString($xml);
|
||||
|
||||
// Convert XML to an array
|
||||
|
||||
$reader->values(); // ['breakfast_menu' => [['name' => '...'], ['name' => '...'], ['name' => '...']]
|
||||
|
||||
// Query the XML
|
||||
|
||||
$reader->value('food.0')->sole(); // ['name' => 'Belgian Waffles', 'price' => '$5.95', ...]
|
||||
|
||||
$reader->xpathValue('//food[@bestSeller="true"]/name')->get(); // ['Belgian Waffles', 'Berry-Berry Belgian Waffles']
|
||||
|
||||
$reader->element('food.0')->sole()->getAttributes(); // ['soldOut' => false, 'bestSeller' => true]
|
||||
```
|
||||
{% endtab %}
|
||||
|
||||
{% tab title="XML" %}
|
||||
```xml
|
||||
<breakfast_menu>
|
||||
<food soldOut="false" bestSeller="true">
|
||||
<name>Belgian Waffles</name>
|
||||
<price>$5.95</price>
|
||||
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
|
||||
<calories>650</calories>
|
||||
</food>
|
||||
<food soldOut="false" bestSeller="false">
|
||||
<name>Strawberry Belgian Waffles</name>
|
||||
<price>$7.95</price>
|
||||
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
|
||||
<calories>900</calories>
|
||||
</food>
|
||||
<food soldOut="false" bestSeller="true">
|
||||
<name>Berry-Berry Belgian Waffles</name>
|
||||
<price>$8.95</price>
|
||||
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
|
||||
<calories>900</calories>
|
||||
</food>
|
||||
</breakfast_menu>
|
||||
```
|
||||
{% endtab %}
|
||||
{% endtabs %}
|
||||
|
||||
### Documentation
|
||||
|
||||
Click the card below to read the documentation
|
||||
|
||||
{% embed url="https://github.com/saloonphp/xml-wrangler" %}
|
||||
|
||||
### Saloon Integration
|
||||
|
||||
XML Wrangler is also integrated with Saloon! Once installed, you'll be able to use the `xmlReader()` method on your responses to instantiate an XML Wrangler reader.
|
||||
|
||||
```php
|
||||
$response = $connector->send($request);
|
||||
|
||||
$reader = $response->xmlReader();
|
||||
|
||||
// $reader->values();
|
||||
// etc...
|
||||
```
|
||||
|
||||
#### Request Body
|
||||
|
||||
You may also choose to use XML Wrangler to create the request body when sending XML requests in Saloon.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Saloon\Http\Request;
|
||||
use Saloon\XmlWrangler\XmlWriter;
|
||||
use Saloon\Contracts\Body\HasBody;
|
||||
use Saloon\Traits\Body\HasXmlBody;
|
||||
use Saloon\XmlWrangler\Data\Element;
|
||||
|
||||
class CreateServerRequest extends Request implements HasBody
|
||||
{
|
||||
use HasXmlBody;
|
||||
|
||||
protected Method $method = Method::POST;
|
||||
|
||||
public function __construct(
|
||||
protected readonly string $ubuntuVersion,
|
||||
protected readonly string $type,
|
||||
protected readonly string $provider
|
||||
){}
|
||||
|
||||
protected function defaultBody(): string
|
||||
{
|
||||
return XmlWriter::make()->write('root', [
|
||||
'ubuntu-version' => $this->ubuntuVersion,
|
||||
'type' => $this->type,
|
||||
'provider' => $this->provider,
|
||||
]);
|
||||
|
||||
// Same as...
|
||||
|
||||
// <?xml version="1.0" encoding="utf-8"?>
|
||||
// <root>
|
||||
// <ubuntu-version>ubuntuVersion</ubuntu-version>
|
||||
// <type>type</type>
|
||||
// <provider>provider</provider>
|
||||
// </root>
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user