Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Api Forge Laravel Package

yusufgenc/filament-api-forge

Expose Filament Resources as REST APIs automatically—no Sanctum. Hash-based API keys with scopes, per-resource access control, rate limiting, IP restrictions, Spatie Query Builder filtering/sorting, and auto-generated OpenAPI + public Swagger docs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require yusufgenc/filament-api-forge
    

    Publish the package config and migrations:

    php artisan vendor:publish --provider="Yusufgenc\FilamentApiForge\FilamentApiForgeServiceProvider"
    php artisan migrate
    
  2. Enable for a Resource: Add HasApi trait to your Filament Resource:

    use Yusufgenc\FilamentApiForge\Traits\HasApi;
    
    class PostResource extends Resource implements HasApi
    {
        // ...
    }
    
  3. First Use Case:

    • Access the Developer Center at /filament-api-forge to generate an API key.
    • Test the auto-generated API endpoint (e.g., GET /api/posts) using the key in the forge_ prefix format (e.g., forge_<hashed-key>).
    • View interactive OpenAPI docs at /api/docs.

Implementation Patterns

Core Workflows

  1. Resource Integration:

    • Auto-Discovery: No manual route registration needed. Resources implementing HasApi are automatically exposed.
    • Customization: Override default API behavior via:
      public static function getApiConfig(): array
      {
          return [
              'enabled' => true,
              'auth' => 'api', // or 'public'
              'rate_limit' => 'high',
              'ip_restrictions' => ['192.168.1.1'],
          ];
      }
      
  2. Authentication:

    • Hash-Based Tokens: Generate via the API Keys panel in the Developer Center.
    • Usage: Pass tokens as a header (forge_<token>) or query param (forge_token).
    • Fallback: Supports Sanctum/Laravel Passport if configured in config/filament-api-forge.php.
  3. Query Builder Support:

    • Leverage Filament’s built-in query builder for filtering/sorting/pagination:
      GET /api/posts?filter[status]=published&sort=-created_at&page=1
      
  4. Access Control:

    • Per-Resource Policies: Define in getApiConfig():
      'access_control' => [
          'create' => 'admin',
          'update' => 'editor',
          'delete' => 'super-admin',
      ],
      
    • Global Policies: Use Laravel’s can() gates or Filament’s authorizeResource() methods.
  5. Rate Limiting:

    • Configure globally (config/filament-api-forge.php) or per-resource:
      'rate_limit' => 'high', // 'low', 'medium', 'high', or custom
      
  6. Documentation:

    • Interactive Docs: Auto-generated at /api/docs (Swagger UI).
    • Public Docs: Enable via config to expose docs without auth:
      'public_docs' => true,
      

Integration Tips

  • Testing: Use forge_ tokens in PHPUnit tests:
    $response = $this->withHeaders(['Authorization' => 'forge_' . $apiKeyHash])
        ->getJson('/api/posts');
    
  • Caching: Enable API response caching for read-heavy endpoints:
    public static function getApiConfig(): array
    {
        return ['cache' => true];
    }
    
  • Webhooks: Trigger API calls from Filament actions:
    public static function getRelations(): array
    {
        return [
            // ...
            Tables\Actions\Action::make('notify')
                ->url(fn (Post $record) => route('api.posts.notify', $record))
                ->openUrlInNewTab(),
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Token Hashing:

    • Tokens are SHA-256 hashed at rest. Never store plaintext keys in logs or client-side code.
    • Debugging: Use the API Keys panel to regenerate tokens if compromised.
  2. CORS Issues:

    • Ensure your Filament app’s CORS config (config/cors.php) allows API routes:
      'paths' => ['api/*', 'filament-api-forge/*'],
      
  3. Rate Limiting:

    • Default limits are strict. Adjust in config/filament-api-forge.php:
      'rate_limits' => [
          'low' => '5/minute',
          'medium' => '20/minute',
          'high' => '60/minute',
      ],
      
    • Bypass: Set 'rate_limit' => null in getApiConfig() for unauthenticated routes.
  4. Query Builder Conflicts:

    • Avoid reserved query params (e.g., filter[resource]). Use underscores for custom filters:
      GET /api/posts?filter[is_featured]=true
      
  5. Filament Admin Access:

    • The Developer Center requires Filament admin access. Restrict via Filament’s canAccessDashboard() if needed.

Debugging

  • Logs: Enable debug mode in config/filament-api-forge.php:

    'debug' => env('APP_DEBUG', false),
    

    Check storage/logs/laravel.log for API-related errors.

  • API Responses:

    • Non-200 responses include error details in JSON:
      {
        "message": "Unauthorized",
        "errors": {
          "auth": ["Invalid API key"]
        }
      }
      
  • Route Debugging:

    • List all API routes with:
      php artisan route:list --path=api
      

Extension Points

  1. Custom API Routes: Override auto-generated routes by binding a controller:

    Route::get('/custom-posts', [CustomPostController::class, 'index'])
        ->middleware('filament-api-forge.auth');
    
  2. Authentication Providers: Extend the HashAuthProvider for custom logic:

    // app/Providers/FilamentApiForgeServiceProvider.php
    public function boot()
    {
        $this->app->extend('filament-api-forge.auth', fn () => new CustomAuthProvider());
    }
    
  3. Documentation Extensions: Add custom OpenAPI schemas via Filament’s registerResources():

    FilamentApiForge::extendDocs(function (OpenApi $openApi) {
        $openApi->info->title('My Custom API');
    });
    
  4. Event Listeners: Listen to API events (e.g., ApiRequestHandled):

    event(new ApiRequestHandled($request, $response));
    

Pro Tips

  • Environment-Specific Keys: Use .env to toggle API features:
    FILAMENT_API_FORGE_ENABLED=false
    
  • Performance: Disable api auth for public read-only endpoints:
    'auth' => 'none',
    
  • Security: Combine with Laravel’s throttle middleware for additional protection:
    Route::middleware(['throttle:60,1'])->group(...);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc