PHP code example of systemverk / laravel-api-usage

1. Go to this page and download the library: Download systemverk/laravel-api-usage library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

systemverk / laravel-api-usage example snippets


ApiUsage::usage()
    ->thisMonth()
    ->forActor(UsageActor::organization(42))
    ->summary();

$summary->totalRequests;      // 18420
$summary->serverErrors;       // 3
$summary->averageDurationMs;  // 46.7
$summary->errorRate();        // 0.0121

use Systemverk\LaravelApiUsage\Actors\AuthenticatedUserActorResolver;

use Illuminate\Http\Request;
use Systemverk\LaravelApiUsage\Actors\UsageActor;
use Systemverk\LaravelApiUsage\Contracts\ResolvesUsageActor;

final class OrganizationActorResolver implements ResolvesUsageActor
{
    public function resolve(Request $request): ?UsageActor
    {
        $organizationId = $request->user()?->organization_id;

        if (! $organizationId) {
            return UsageActor::guest();
        }

        return UsageActor::make('organization', $organizationId);
    }
}

// config/api_usage.php
'actor' => [
    'resolver' => OrganizationActorResolver::class,
],

// app/Providers/AppServiceProvider.php
use Illuminate\Http\Request;
use Systemverk\LaravelApiUsage\Support\UsageRecorder;

public function boot(): void
{
    UsageRecorder::resolveCredentialUsing(
        fn (Request $request) => $request->user()?->currentAccessToken()?->getKey()
    );
}

// Everything one team did this month, across all of its keys
ApiUsage::usage()->thisMonth()->forActor(UsageActor::make('team', $team->id))->summary();

// Just one key
ApiUsage::usage()->thisMonth()->forCredential($token->id)->summary();

$thisMonth = ApiUsage::usage()->thisMonth();

$acme = $thisMonth->forActor(UsageActor::organization(1))->summary();
$globex = $thisMonth->forActor(UsageActor::organization(2))->summary();

ApiUsage::usage()->lastDays(7)->summary();  // UsageSummary
ApiUsage::usage()->thisMonth()->count();    // int

ApiUsage::endpoints()->thisMonth()->mostUsed();      // Collection<EndpointUsage>
ApiUsage::endpoints()->thisMonth()->slowest(5);
ApiUsage::endpoints()->thisMonth()->mostErrors();
ApiUsage::endpoints()->thisMonth()->all();

ApiUsage::actors()->lastDays(30)->mostActive();
ApiUsage::actors()->lastDays(30)->mostErrors();
ApiUsage::actors()->lastDays(30)->forActorType('organization')->mostActive();

use Systemverk\LaravelApiUsage\Models\ApiUsageRequest;
use Systemverk\LaravelApiUsage\Models\ApiUsageSummary;

// Slowest concrete paths in the last 24 hours
ApiUsageRequest::query()
    ->where('requested_at', '>=', now()->utc()->subDay())
    ->selectRaw('path, count(*) as hits, avg(duration_ms) as avg_ms')
    ->groupBy('path')
    ->orderByDesc('avg_ms')
    ->limit(10)
    ->get();

// Server errors today
ApiUsageRequest::query()->statusClass(5)->whereDate('requested_at', today())->count();

// Monthly rollups for one actor
ApiUsageSummary::query()->monthly()->forActor(UsageActor::organization(42))->get();

'except' => ['up', 'health', 'webhooks/*'],

'sampling' => ['rate' => 0.1], // record roughly one request in ten

// bootstrap/app.php
use Systemverk\LaravelApiUsage\Http\Middleware\RecordApiUsage;

->withMiddleware(function (Middleware $middleware) {
    $middleware->api(append: [RecordApiUsage::class]);
})

// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('api-usage:flush --max-minutes=5')->everyMinute()->withoutOverlapping();
Schedule::command('api-usage:consolidate-daily --today')->hourly()->withoutOverlapping();
Schedule::command('api-usage:consolidate-daily')->dailyAt('02:00');
Schedule::command('api-usage:consolidate-monthly')->monthlyOn(1, '03:00');
Schedule::command('api-usage:prune')->dailyAt('03:10');
bash
php artisan migrate
bash
php artisan api-usage:status
bash
php artisan api-usage:consolidate-daily --today
bash
php artisan vendor:publish --tag=api-usage-config