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

Php Youtube Api Laravel Package

madcoda/php-youtube-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require madcoda/php-youtube-api
    

    Add the package to composer.json and run composer update.

  2. First Use Case: Fetching a Video

    use Madcoda\YouTube\YouTube;
    
    $youtube = new YouTube('YOUR_API_KEY');
    $video = $youtube->videos->get('VIDEO_ID');
    echo $video->title;
    
  3. Key Files to Explore

    • src/YouTube.php: Main class for API initialization.
    • src/Resources/Videos.php: Video-related methods (e.g., search, upload, comments).
    • src/Resources/Playlists.php: Playlist operations.
    • src/Resources/Channels.php: Channel data retrieval.

Implementation Patterns

Common Workflows

1. Searching Videos

$search = $youtube->videos->search('laravel', [
    'type' => 'video',
    'maxResults' => 5,
]);
foreach ($search as $item) {
    echo $item->title . "\n";
}

2. Uploading a Video

use Madcoda\YouTube\Upload\Video;

$upload = new Video($youtube, [
    'title' => 'My Laravel Tutorial',
    'description' => 'Learn Laravel basics',
    'file' => fopen('video.mp4', 'r'),
]);
$upload->upload();

3. Handling Playlists

// Create a playlist
$playlist = $youtube->playlists->create('My Laravel Playlist');

// Add video to playlist
$youtube->playlistItems->insert('PLAYLIST_ID', 'VIDEO_ID');

4. Channel Subscriptions

// Subscribe to a channel
$youtube->subscriptions->insert('CHANNEL_ID');

// List subscriptions
$subscriptions = $youtube->subscriptions->list();

Integration Tips

  • Caching Responses: Use Laravel’s cache to store API responses (e.g., Cache::remember()).
  • Error Handling: Wrap API calls in try-catch blocks to handle Madcoda\YouTube\Exception\YouTubeException.
  • Rate Limiting: Monitor quota usage via $youtube->getQuota() and implement retries for quotaExceeded errors.
  • Laravel Service Provider: Bind the YouTube instance in a service provider for dependency injection:
    $this->app->singleton(YouTube::class, function ($app) {
        return new YouTube(config('services.youtube.api_key'));
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Management

    • Hardcoding API keys in code violates security best practices. Use Laravel’s .env:
      YOUTUBE_API_KEY=your_key_here
      
    • Restrict the API key to only the YouTube Data API in the Google Cloud Console.
  2. Rate Limits

    • The free tier has strict quotas (e.g., 10,000 units/day). Exceeding limits returns 403 Forbidden.
    • Fix: Implement exponential backoff or use a queue (e.g., Laravel Queues) for batch operations.
  3. Deprecated Methods

    • Some methods (e.g., videos->getById()) may not exist in newer API versions. Refer to the official YouTube API docs for updates.
  4. File Uploads

    • Large video uploads (>20MB) require chunked uploads. The package supports this via Madcoda\YouTube\Upload\Video, but test with small files first.
  5. Time Zones and Dates

    • API responses use ISO 8601 timestamps. Convert to local time with Carbon:
      use Carbon\Carbon;
      $publishedAt = Carbon::parse($video->publishedAt);
      

Debugging Tips

  • Enable Debugging: Set the debug option in the constructor:

    $youtube = new YouTube('API_KEY', ['debug' => true]);
    

    Logs HTTP requests/responses to storage/logs/youtube.log.

  • Common Errors:

    • 400 Bad Request: Validate parameters (e.g., part field in requests).
    • 403 Forbidden: Check API key permissions or quota.
    • 404 Not Found: Verify IDs (e.g., video/playlist IDs).

Extension Points

  1. Custom Responses Override the default response handling by extending the Madcoda\YouTube\YouTube class:

    class CustomYouTube extends YouTube {
        protected function handleResponse($response) {
            // Custom logic (e.g., transform data)
            return parent::handleResponse($response);
        }
    }
    
  2. Adding New Resources The package follows a modular structure. To add support for a new API endpoint (e.g., activities):

    • Extend Madcoda\YouTube\Resource\AbstractResource.
    • Register the new resource in YouTube.php.
  3. Mocking for Testing Use Laravel’s HTTP mocking or create a decorator for the YouTube class:

    $mockYoutube = Mockery::mock(YouTube::class)->makePartial();
    $mockYoutube->shouldReceive('videos->get')->andReturn($mockVideo);
    
  4. Webhooks The package doesn’t support webhooks natively, but you can use the Google Cloud Pub/Sub or YouTube Notification API for real-time updates.

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.
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
christhompsontldr/laravel-inky