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-php/open-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jane-php/open-api
    

    (Note: Due to archival, verify compatibility with your PHP/Laravel version—last release was 2018.)

  2. Generate Client Place your OpenAPI 3.x spec (e.g., api.yaml) in your project. Run:

    vendor/bin/jane --spec=api.yaml --output=src/Generated/Client
    

    (Outputs a PSR7/PSR18-compatible client in src/Generated/Client.)

  3. First Use Case Register the generated client in Laravel’s AppServiceProvider:

    public function register()
    {
        $this->app->singleton('api.client', function () {
            return new \Generated\Client\Client(
                new \GuzzleHttp\Client(),
                'https://api.example.com'
            );
        });
    }
    

    Inject and use it in a controller:

    use Generated\Client\Api\UsersApi;
    
    public function fetchUsers(UsersApi $usersApi)
    {
        $response = $usersApi->getUsers();
        return response()->json($response->getBody());
    }
    

Implementation Patterns

Core Workflows

  1. Request/Response Handling Use the generated client’s methods (e.g., getUsers(), createUser()) to interact with the API. Responses are PSR7-compatible (Psr\Http\Message\ResponseInterface):

    $response = $usersApi->getUsers(['limit' => 10]);
    $data = json_decode($response->getBody(), true);
    
  2. Authentication Pass credentials via middleware or headers:

    $client = new \Generated\Client\Client(
        new \GuzzleHttp\Client([
            'headers' => ['Authorization' => 'Bearer ' . $token]
        ]),
        'https://api.example.com'
    );
    
  3. Error Handling Wrap API calls in try-catch blocks to handle exceptions (e.g., Generated\Client\Exception\ApiException):

    try {
        $usersApi->deleteUser(123);
    } catch (\Generated\Client\Exception\ApiException $e) {
        report($e);
        return back()->withError($e->getMessage());
    }
    
  4. Laravel Integration

    • Service Providers: Bind the client to the container for dependency injection.
    • Middleware: Use Laravel’s middleware to transform requests/responses (e.g., add default headers):
      public function handle($request, Closure $next)
      {
          $request->headers->set('X-Custom-Header', 'value');
          return $next($request);
      }
      
  5. Testing Mock the generated client in tests:

    $mockClient = Mockery::mock(\Generated\Client\Client::class);
    $this->app->instance(\Generated\Client\Client::class, $mockClient);
    

Gotchas and Tips

Pitfalls

  1. Archived Package

    • No active maintenance; test thoroughly with your OpenAPI spec version.
    • Fork and update dependencies if needed (e.g., PSR7/PSR18 compatibility).
  2. Generated Code Overrides

    • Regenerating the client (vendor/bin/jane) overwrites the output directory. Use version control for the Generated/ folder or exclude it from regeneration.
  3. OpenAPI 3.x Quirks

    • The package primarily supports OpenAPI 2.0 (Swagger). For 3.x, ensure your spec is compatible or pre-process it (e.g., use openapi-to-swagger tools).
    • Complex schemas (e.g., $ref with dynamic paths) may require manual adjustments in the generated code.
  4. PSR18 Compatibility

    • The package defaults to PSR7. For PSR18 (HTTP client interfaces), wrap the Guzzle client:
      use Psr\Http\Client\ClientInterface;
      use Nyholm\Psr7\Client;
      
      $psr18Client = new Client(new \GuzzleHttp\Client());
      
  5. Caching Responses

    • Manually cache responses to avoid redundant API calls:
      $cacheKey = 'users_' . $limit;
      return Cache::remember($cacheKey, now()->addHours(1), function () use ($usersApi, $limit) {
          return $usersApi->getUsers(['limit' => $limit]);
      });
      

Debugging Tips

  1. Enable Guzzle Debugging Add a debug handler to Guzzle’s middleware stack:

    $client = new \GuzzleHttp\Client([
        'handler' => \GuzzleHttp\HandlerStack::create(
            new \GuzzleHttp\Middleware::tap(function ($request) {
                \Log::debug('Request:', [
                    'url' => (string) $request->getUri(),
                    'method' => $request->getMethod(),
                    'headers' => $request->getHeaders(),
                    'body' => (string) $request->getBody()
                ]);
            })
        )
    ]);
    
  2. Validate OpenAPI Spec Use tools like Swagger Editor or spectral to validate your spec before generation.

  3. Generated Client Logs Enable debug mode in the generated client by setting the DEBUG constant:

    define('DEBUG', true);
    

Extension Points

  1. Custom Middleware Extend the client’s middleware stack to add logging, retries, or auth:

    $client = new \Generated\Client\Client(
        new \GuzzleHttp\Client([
            'middleware' => [
                new \GuzzleHttp\Middleware(),
                new class {
                    public function __invoke(
                        callable $handler,
                        \Psr\Http\Message\RequestInterface $request
                    ) {
                        // Custom logic (e.g., add timestamp header)
                        $request = $request->withHeader('X-Request-Timestamp', now()->toIso8601String());
                        return $handler($request);
                    }
                }
            ]
        ]),
        'https://api.example.com'
    );
    
  2. Modify Generated Code Use template overrides to customize the generated client. Create a templates/ directory with modified .mustache files and pass the --template-dir flag to jane.

  3. Laravel Facades Create a facade for cleaner syntax:

    // ApiFacade.php
    class ApiFacade extends \Illuminate\Support\Facades\Facade
    {
        protected static function getFacadeAccessor() { return 'api.client'; }
    }
    

    Usage:

    $users = Api::users()->getUsers();
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity