Installation
composer require anh/sape-php-client
Add the service provider to config/app.php:
'providers' => [
Anh\SapeClient\SapeServiceProvider::class,
],
Configuration Publish the config file:
php artisan vendor:publish --provider="Anh\SapeClient\SapeServiceProvider"
Update .env with your SAPE API credentials:
SAPE_API_KEY=your_api_key_here
SAPE_API_SECRET=your_api_secret_here
First Use Case: Fetching a User
use Anh\SapeClient\Facades\Sape;
$user = Sape::user()->get(123);
dd($user);
CRUD Operations
// Create
$user = Sape::user()->create(['name' => 'John Doe', 'email' => 'john@example.com']);
// Read
$users = Sape::user()->all();
// Update
$updated = Sape::user()->update(123, ['email' => 'new@example.com']);
// Delete
Sape::user()->delete(123);
API Resource Handling
Use the resource() method to interact with custom endpoints:
$orders = Sape::resource('orders')->all();
Pagination
$users = Sape::user()->paginate(10);
Query Parameters
$users = Sape::user()->get(['active' => true, 'role' => 'admin']);
Laravel Eloquent Integration Extend the package to work with Eloquent models:
class User extends Model {
public static function fetchFromSape($id) {
return Sape::user()->get($id);
}
}
Middleware for API Calls Create middleware to handle API rate limits or authentication:
namespace App\Http\Middleware;
use Anh\SapeClient\Facades\Sape;
use Closure;
class SapeAuthMiddleware {
public function handle($request, Closure $next) {
Sape::setApiKey(config('sape.api_key'));
return $next($request);
}
}
Authentication Errors
Ensure .env credentials are correct. Test with:
Sape::auth()->validate();
Rate Limiting The package may not handle rate limits automatically. Implement retry logic:
use Anh\SapeClient\Exceptions\RateLimitExceeded;
try {
$data = Sape::user()->get(123);
} catch (RateLimitExceeded $e) {
sleep(60); // Wait and retry
$data = Sape::user()->get(123);
}
Endpoint Mismatches
Verify endpoint names in the config (config/sape.php) match the API’s actual endpoints.
Enable Debug Mode
Sape::setDebug(true); // Logs all API requests/responses
Check Raw Responses
$response = Sape::user()->get(123, [], true); // Returns raw response
Custom Requests
Extend the Anh\SapeClient\Requests\Request class to add custom logic:
namespace App\Sape;
use Anh\SapeClient\Requests\Request;
class CustomRequest extends Request {
public function getHeaders() {
return array_merge(parent::getHeaders(), ['X-Custom-Header' => 'value']);
}
}
Override API Base URL Dynamically change the base URL:
Sape::setBaseUrl('https://custom-api.sape.com');
Add New Resources
Register new resources in the service provider’s boot() method:
Sape::extend('custom_resource', function () {
return new CustomResource();
});
How can I help you explore Laravel packages today?