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

Open Api Runtime Laravel Package

jane-php/open-api-runtime

Runtime dependencies and utility classes used by clients generated with Jane OpenAPI. Provides shared infrastructure for request/response handling, serialization, and other common helpers so generated SDKs work consistently without duplicating code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jane-php/open-api-runtime
    

    Ensure your project uses Jane OpenAPI generator (e.g., janephp/janephp) to scaffold API clients.

  2. First Use Case: Generate a client from your OpenAPI spec (e.g., swagger.json):

    vendor/bin/jane generate:client --spec=swagger.json --output=src/ApiClient
    

    This creates a src/ApiClient directory with a pre-configured runtime client.

  3. Basic Usage:

    use ApiClient\Client;
    use ApiClient\Api\YourApi;
    
    $client = new Client();
    $api = new YourApi($client);
    
    $response = $api->yourEndpoint(['param' => 'value']);
    

Where to Look First

  • Generated Client: Check the src/ApiClient directory for auto-generated API classes.
  • Runtime Docs: Jane OpenAPI Documentation for runtime behavior.
  • Config: Look for config.php or ClientConfig classes in the generated code.

Implementation Patterns

Workflows

  1. Request Handling: Use the generated API classes to interact with endpoints. The runtime handles:

    • Serialization/deserialization (JSON/XML).
    • Authentication (OAuth, API keys via config).
    • HTTP client abstraction (Guzzle by default).
    // Example: POST request with body
    $response = $api->createResource([
        'name' => 'Test',
        'description' => 'Example'
    ]);
    
  2. Middleware Integration: Extend the runtime’s middleware stack (e.g., for logging or auth):

    use ApiClient\Middleware\MiddlewareInterface;
    
    class CustomAuthMiddleware implements MiddlewareInterface {
        public function handle($request, callable $next) {
            $request->headers['X-Custom-Auth'] = 'token';
            return $next($request);
        }
    }
    
    // Register in ClientConfig
    $client->setMiddleware([new CustomAuthMiddleware()]);
    
  3. Error Handling: Catch runtime exceptions (e.g., ApiException) and validate responses:

    try {
        $response = $api->deleteResource(123);
    } catch (\ApiClient\Exception\ApiException $e) {
        if ($e->getCode() === 404) {
            // Handle not found
        }
    }
    
  4. Testing: Mock the runtime client for unit tests:

    use ApiClient\Client;
    use ApiClient\Exception\ApiException;
    
    $mockClient = $this->createMock(Client::class);
    $mockClient->method('send')
        ->willReturn(new \stdClass()); // Mock response
    
    $api = new YourApi($mockClient);
    

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    public function register() {
        $this->app->singleton(Client::class, function ($app) {
            return new Client(new \GuzzleHttp\Client(), $app['config']['api']);
        });
    }
    
  • Dynamic Config: Load OpenAPI config from Laravel’s config/api.php:

    $client = new Client(new \GuzzleHttp\Client(), config('api'));
    
  • Event Dispatching: Trigger events before/after requests (e.g., for analytics):

    $client->on('request', function ($request) {
        event(new ApiRequestEvent($request));
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated Runtime:

    • Last release in 2018; ensure compatibility with your OpenAPI spec version (e.g., v2/v3).
    • May lack support for newer OpenAPI features (e.g., WebSockets, GraphQL).
  2. Generated Code Overrides:

    • Avoid modifying auto-generated classes directly. Extend them instead:
      class ExtendedApi extends \ApiClient\Api\YourApi {
          public function customMethod() { ... }
      }
      
  3. HTTP Client Lock-in:

    • Defaults to Guzzle. Switching clients (e.g., Symfony HTTP Client) requires middleware rewrites.
  4. Caching Quirks:

    • Runtime caches responses by default. Disable with:
      $client->setCacheEnabled(false);
      

Debugging

  • Enable Verbose Logging:

    $client->setLogger(new \Monolog\Logger('api', [
        new \Monolog\Handler\StreamHandler('php://stdout', \Monolog\Logger::DEBUG)
    ]));
    
  • Inspect Requests: Use middleware to log raw requests/responses:

    $client->setMiddleware([new class implements MiddlewareInterface {
        public function handle($request, callable $next) {
            \Log::debug('Request:', $request->toArray());
            return $next($request);
        }
    }]);
    

Extension Points

  1. Custom Serializers: Override default JSON/XML serialization:

    $client->setSerializer(new \ApiClient\Serializer\CustomSerializer());
    
  2. Plugin System: Extend the runtime via plugins (e.g., for rate limiting):

    $client->addPlugin(new \ApiClient\Plugin\RateLimitPlugin());
    
  3. Async Support: Use ReactPHP for async requests (requires custom middleware):

    $loop = \React\EventLoop\Factory::create();
    $client->setHttpClient(new \React\Http\Client($loop));
    

Configuration Quirks

  • Base Paths: Set global base paths in ClientConfig:

    $client->setBasePath('/api/v1');
    
  • Security Schemes: Define auth schemes in the OpenAPI spec or via config:

    $client->setSecuritySchemes(['api_key' => ['name' => 'Authorization', 'in' => 'header']]);
    
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings