Weave Code
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

Openapi Laravel Package

splash/openapi

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require splash/openapi
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Splash\OpenApi\OpenApiServiceProvider"
    
  2. First Use Case: Generating a Client Use the OpenApiClientGenerator to create a client from an OpenAPI spec:

    use Splash\OpenApi\OpenApiClientGenerator;
    
    $generator = new OpenApiClientGenerator();
    $client = $generator->generateClientFromSpec('path/to/openapi.json');
    
  3. Key Classes to Explore

    • OpenApiClientGenerator: Core class for client generation.
    • OpenApiRequest: Handles API requests with OpenAPI specs.
    • OpenApiResponse: Processes API responses.
    • OpenApiSchema: Manages schema validation and parsing.

Implementation Patterns

Workflow: API Integration

  1. Spec-Based Client Generation Dynamically generate a client from an OpenAPI spec (YAML/JSON) at runtime or during deployment:

    $client = $generator->generateClientFromSpec(config('openapi.spec_path'));
    
  2. Request Handling Use OpenApiRequest to send requests with automatic schema validation:

    $request = new OpenApiRequest($client, 'get', '/users/{id}', ['id' => 1]);
    $response = $request->send();
    
  3. Response Processing Parse and validate responses using OpenApiResponse:

    $data = $response->getData();
    $response->validateSchema($client->getSchema('User'));
    
  4. Middleware Integration Attach middleware (e.g., auth, logging) to requests:

    $request->addMiddleware(new AuthMiddleware());
    

Common Patterns

  • Schema Validation: Validate requests/responses against OpenAPI schemas.
  • Dynamic Endpoint Discovery: Use the spec to list available endpoints.
  • Mocking for Testing: Generate mock clients for unit/integration tests.
  • Swagger UI Integration: Serve OpenAPI specs for documentation (e.g., via darkaonline/l5-swagger).

Laravel-Specific Tips

  • Service Provider Binding: Bind the generator to the container for dependency injection:
    $this->app->bind(OpenApiClientGenerator::class, function ($app) {
        return new OpenApiClientGenerator(config('openapi.spec_path'));
    });
    
  • Configurable Spec Path: Store the OpenAPI spec path in config/openapi.php:
    'spec_path' => storage_path('app/openapi/spec.json'),
    

Gotchas and Tips

Pitfalls

  1. Schema Mismatches

    • Issue: Request/response data may not match the OpenAPI schema, causing silent failures.
    • Fix: Always call validateSchema() on responses and use OpenApiRequest::validate() for requests.
    • Debugging: Enable strict validation in config:
      'validation' => [
          'strict' => true,
      ],
      
  2. Caching Generated Clients

    • Issue: Regenerating clients on every request is inefficient.
    • Fix: Cache the generated client (e.g., using Laravel's cache):
      $client = Cache::remember('openapi_client', now()->addHours(1), function () {
          return $generator->generateClientFromSpec(config('openapi.spec_path'));
      });
      
  3. Deprecated OpenAPI Features

    • Issue: Older OpenAPI specs (e.g., Swagger 1.2) may not work.
    • Fix: Ensure your spec is OpenAPI 3.x compliant. Use tools like Swagger Editor to validate.
  4. Middleware Order

    • Issue: Middleware may not execute in the expected order.
    • Fix: Explicitly set middleware priority:
      $request->addMiddleware(new LoggingMiddleware(), 'last');
      

Debugging Tips

  • Enable Verbose Logging: Set the debug flag in config to log request/response details:
    'debug' => env('APP_DEBUG', false),
    
  • Inspect Generated Client: Dump the client object to understand its structure:
    dd($client->getOperations());
    
  • Validate Spec Locally: Use tools like spectral or openapi-linter to validate specs before runtime.

Extension Points

  1. Custom Schema Validators Extend OpenApiSchema to add custom validation rules:

    class CustomSchema extends OpenApiSchema {
        public function validateCustomRule($data) {
            // Custom logic
        }
    }
    
  2. Plugin System Use Laravel's service provider to register custom plugins:

    OpenApiClientGenerator::extend(function ($generator) {
        $generator->addPlugin(new MyCustomPlugin());
    });
    
  3. Event Listeners Listen to OpenApi.RequestSent or OpenApi.ResponseReceived events for logging/auditing:

    event(new OpenApiRequestSent($request));
    

Performance Considerations

  • Spec Parsing: Parse the OpenAPI spec once and cache it (e.g., using Laravel's config_cache).
  • Lazy-Loading: Load schemas/endpoints only when needed to reduce memory usage.
  • Async Requests: Use Laravel Queues for long-running API calls to avoid timeouts.
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.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed