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

Guzzle Rottentomatoes Client Laravel Package

devmachine/guzzle-rottentomatoes-client

Lightweight PHP client for the Rotten Tomatoes API built on Guzzle 4. Create a client with your API key and call endpoints like movies search (e.g., query by title) to get structured movie data (ratings, release dates, posters, cast).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require devmachine/guzzle-rottentomatoes-client:1.0.*
    

    Ensure your composer.json includes the package under require.

  2. API Key Setup:

    • Obtain an API key from Rotten Tomatoes Developer Portal.
    • Store it securely (e.g., .env file) and retrieve it via Laravel’s config() helper or environment variables.
  3. First Use Case: Fetch movie data for a specific title (e.g., "Terminator 3"):

    use Devmachine\Guzzle\RottenTomatoes\RottenTomatoesClient;
    
    $client = RottenTomatoesClient::factory(config('services.rottentomatoes.api_key'));
    $result = $client->movies(['q' => 'Terminator 3']);
    return $result['movies'][0]['title']; // Output: "Terminator 3 - Rise of the Machines"
    
  4. Key Files:

    • vendor/devmachine/guzzle-rottentomatoes-client/src/Devmachine/Guzzle/RottenTomatoes/RottenTomatoesClient.php (core logic).
    • Interactive API Docs for endpoint reference.

Implementation Patterns

Workflows

  1. Service Layer Integration: Create a Laravel service class to abstract API calls:

    namespace App\Services;
    
    use Devmachine\Guzzle\RottenTomatoes\RottenTomatoesClient;
    
    class RottenTomatoesService {
        protected $client;
    
        public function __construct() {
            $this->client = RottenTomatoesClient::factory(config('services.rottentomatoes.api_key'));
        }
    
        public function getMovieByTitle(string $title) {
            return $this->client->movies(['q' => $title]);
        }
    }
    

    Register the service in AppServiceProvider:

    public function register() {
        $this->app->singleton(RottenTomatoesService::class, function ($app) {
            return new RottenTomatoesService();
        });
    }
    
  2. Query Builder Pattern: Use the client’s methods to chain queries (e.g., fetch a movie and its reviews):

    $movie = $this->rottentomatoesService->getMovieByTitle('Inception');
    $reviews = $this->rottentomatoesService->client->movieReviews($movie['movies'][0]['id']);
    
  3. Pagination Handling: Manually paginate results (since Guzzle 4 lacks built-in pagination):

    $page = 1;
    $results = [];
    while (true) {
        $response = $this->rottentomatoesService->client->movies(['page' => $page, 'q' => 'action']);
        if (empty($response['movies'])) break;
        $results = array_merge($results, $response['movies']);
        $page++;
    }
    
  4. Caching Responses: Cache API responses to reduce calls (e.g., using Laravel’s cache):

    $cacheKey = "rottentomatoes_movie_{$title}";
    $movie = cache()->remember($cacheKey, now()->addHours(1), function () use ($title) {
        return $this->rottentomatoesService->getMovieByTitle($title);
    });
    
  5. Error Handling: Wrap API calls in try-catch blocks to handle Guzzle exceptions:

    try {
        $result = $this->rottentomatoesService->client->movies(['q' => 'nonexistent']);
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        Log::error("RottenTomatoes API Error: " . $e->getMessage());
        return response()->json(['error' => 'API request failed'], 500);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Guzzle Version:

    • The package uses Guzzle 4, which lacks features like resource iterators (pagination) present in Guzzle 3.
    • Workaround: Manually implement pagination loops (as shown above).
  2. API Key Exposure:

    • Hardcoding API keys in client initialization is risky.
    • Fix: Use Laravel’s .env and config/services.php:
      ROTTENTOMATOES_API_KEY=your_api_key_here
      
      // config/services.php
      'rottentomatoes' => [
          'api_key' => env('ROTTENTOMATOES_API_KEY'),
      ];
      
  3. Rate Limiting:

    • Rotten Tomatoes API has rate limits.
    • Tip: Implement exponential backoff for retries:
      use GuzzleHttp\Exception\TooManyRequestsException;
      
      try {
          $response = $client->movies(['q' => 'test']);
      } catch (TooManyRequestsException $e) {
          sleep(2); // Wait before retrying
          retry();
      }
      
  4. Endpoint Changes:

    • The package may not cover all endpoints (e.g., newer Rotten Tomatoes APIs).
    • Tip: Extend the client by subclassing RottenTomatoesClient:
      namespace App\Services;
      
      use Devmachine\Guzzle\RottenTomatoes\RottenTomatoesClient;
      
      class ExtendedRottenTomatoesClient extends RottenTomatoesClient {
          public function customEndpoint(array $params = []) {
              return $this->request('GET', '/custom/endpoint', $params);
          }
      }
      
  5. Data Parsing:

    • API responses may return null or empty arrays for missing fields.
    • Tip: Use Laravel’s data_get helper for safe access:
      $rating = data_get($movie, 'ratings.critics_score', 0);
      

Debugging Tips

  1. Enable Guzzle Debugging: Add a middleware to log requests/responses:

    $client->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request) {
            Log::debug('RottenTomatoes Request:', [
                'url' => (string) $request->getUri(),
                'params' => $request->getQuery(),
            ]);
        })
    );
    
  2. Validate API Responses: Use Laravel’s Validator to ensure response structure:

    $validator = Validator::make($result, [
        'movies.*.id' => 'required|string',
        'movies.*.title' => 'required|string',
    ]);
    
  3. Test Locally: Use Rotten Tomatoes’ sandbox to test endpoints before production.

Extension Points

  1. Custom Requests: Override the request method to add headers or modify requests:

    class CustomRottenTomatoesClient extends RottenTomatoesClient {
        protected function request($method, $uri, array $options = []) {
            $options['headers']['X-Custom-Header'] = 'value';
            return parent::request($method, $uri, $options);
        }
    }
    
  2. Response Transformers: Convert API responses to Eloquent models or DTOs:

    $movieData = $this->rottentomatoesService->getMovieByTitle('Interstellar');
    $movie = (new MovieTransformer())->transform($movieData['movies'][0]);
    
  3. Mocking for Tests: Use Laravel’s Mockery to mock the client in tests:

    $mockClient = Mockery::mock(RottenTomatoesClient::class);
    $mockClient->shouldReceive('movies')
               ->once()
               ->andReturn(['movies' => [$fakeMovieData]]);
    $this->app->instance(RottenTomatoesClient::class, $mockClient);
    
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