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

Open Api Laravel Package

jane/open-api

Deprecated package for generating API clients/models from OpenAPI specs with Jane. This repository is no longer maintained; use the consolidated JanePHP project instead: https://github.com/janephp/janephp

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require jane/open-api
    

    (Note: This package is deprecated; consider migrating to janephp/janephp for active maintenance.)

  2. Generate Client from OpenAPI Spec:

    vendor/bin/openapi --spec=path/to/spec.yaml --output=src/Generated/Client
    
    • --spec: Path to your OpenAPI/Swagger spec (YAML or JSON).
    • --output: Directory to generate client classes (e.g., src/Generated/Client).
  3. First Use Case:

    • Use the generated client in Laravel to interact with an API:
      use Generated\Client\Api\UsersApi;
      use Generated\Client\Model\User;
      
      $client = new UsersApi();
      $response = $client->getUser(1); // Assuming `getUser` is defined in the spec
      $user = User::fromJson($response->getBody());
      

Implementation Patterns

Workflows in Laravel

  1. Autoload Generated Classes: Ensure the generated src/Generated/Client directory is autoloaded in composer.json:

    "autoload": {
        "psr-4": {
            "Generated\\Client\\": "src/Generated/Client/"
        }
    }
    

    Run composer dump-autoload.

  2. Dependency Injection: Bind the generated client to Laravel’s container (e.g., in AppServiceProvider):

    $this->app->bind(
        Generated\Client\Api\UsersApi::class,
        fn($app) => new Generated\Client\Api\UsersApi()
    );
    
  3. Request Customization:

    • Override default HTTP clients (e.g., Guzzle) by extending the generated client:
      use Generated\Client\Api\UsersApi as BaseUsersApi;
      use GuzzleHttp\Client;
      
      class CustomUsersApi extends BaseUsersApi {
          public function __construct() {
              $client = new Client([
                  'base_uri' => config('services.api.base_uri'),
                  'headers' => ['Authorization' => 'Bearer ' . auth()->token()]
              ]);
              parent::__construct($client);
          }
      }
      
  4. Handling Responses:

    • Parse responses using generated models:
      $response = $client->createUser(new User(['name' => 'John']));
      $createdUser = User::fromJson($response->getBody());
      
  5. Error Handling:

    • Catch exceptions thrown by the client (e.g., Generated\Client\ApiException):
      try {
          $client->deleteUser(1);
      } catch (ApiException $e) {
          Log::error('API Error:', ['message' => $e->getMessage()]);
          throw new \RuntimeException('Failed to delete user', 0, $e);
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • The package is archived and lacks updates. Use janephp/janephp for new projects.
  2. PHP Version Compatibility:

    • Requires PHP 7+ (see v2.0.0).
    • Older Laravel versions (e.g., <5.5) may conflict with nikic/php-parser dependencies.
  3. Namespace Collisions:

    • Generated class names may clash if OpenAPI tags contain special characters (e.g., dots). Use --prefix to customize:
      vendor/bin/openapi --prefix=Api --output=src/Generated/
      
  4. YAML Support:

    • While YAML is supported, ensure your spec is valid JSON/YAML. Use tools like swagger-cli to validate first.
  5. AllOf/OneOf Handling:

    • Complex schemas (e.g., allOf, oneOf) may generate incorrect models. Test thoroughly or extend the generator (see #33).
  6. PSR-7 Compliance:

    • The client uses PSR-7 requests/responses. Ensure your Laravel HTTP layer (e.g., Guzzle) is PSR-7 compatible:
      $this->app->singleton(GuzzleHttp\Client::class, fn() => new Client([
          'handler' => new \GuzzleHttp\HandlerStack(),
          'base_uri' => config('api.base_url'),
      ]));
      

Debugging Tips

  1. Verbose Output: Run the generator with --verbose to diagnose issues:

    vendor/bin/openapi --spec=spec.yaml --output=src/ --verbose
    
  2. Custom Configuration: Use a .openapi.php config file to override defaults (e.g., namespace, prefix):

    return [
        'namespace' => 'App\\Generated\\Client',
        'prefix' => 'Api',
        'use_date_time_type' => true,
    ];
    
  3. Handling Missing Responses: If a 200 response is missing in the spec, the generator may throw warnings. Add a default response to the spec:

    responses:
      200:
        description: Success
        schema: {}
    

Extension Points

  1. Custom Model Mapping: Extend generated models to add Laravel-specific logic (e.g., fillable attributes):

    namespace Generated\Client\Model;
    
    class User extends \Generated\Client\Model\User {
        protected $fillable = ['name', 'email'];
    }
    
  2. Middleware Integration: Attach Laravel middleware to API calls by wrapping the client:

    $client = new UsersApi();
    $client->setHttpClient(new MiddlewareClient([
        'middleware' => [
            fn(callable $handler) => function ($request, $options) {
                $request = $request->withHeader('X-Custom-Header', 'value');
                return $handler($request, $options);
            },
        ],
    ]));
    
  3. Dynamic Base URLs: Use Laravel’s config to set the base URL dynamically:

    $client = new UsersApi();
    $client->setBasePath(config('services.api.base_url'));
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php