YouTube API 403 error when website restriction set

I am loading the latest videos from a YouTube channel to WordPress, using the YouTube API:

function load_feed() {
    $url = add_query_arg(
        array(
            'part' => 'snippet',
            'channelId' => '[YouTube channel ID]',
            'maxResults' => 3,
            'order' => 'date',
            'type' => 'video',
            'key' => '[YouTube API key]'
        ),
        'https://www.googleapis.com/youtube/v3/search'
    );

    $response = wp_remote_get(esc_url_raw($url));

    return json_decode(wp_remote_retrieve_body($response), true);
}

Everything works well when in the API settings on Google Developers I have:

Application restrictions: None

But when I set:

Application restrictions: HTTP referrers (web sites)

Website restrictions: www.mysite.com/*

I get the following response from the API:

{
    "error": {
        "code": 403,
        "message": "Requests from referer https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[Channel ID]&maxResults=3&order=date&type=video&key=[API key] are blocked.",
        "errors": [
            {
                "message": "Requests from referer https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[Channel ID]&maxResults=3&order=date&type=video&key=[API key] are blocked.",
                "domain": "global",
                "reason": "forbidden"
            }
        ],
        "status": "PERMISSION_DENIED"
    }
}

It looks as though the API detects the request was made from googleapis.com and not from mysite.com, where I have the WP installation and am running the above code.

Why is this error occurring and what can I do to fix it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you restrict the application (or API key) by HTTP referrers, then your remote HTTP request should include a valid HTTP_REFERER header, which wp_remote_get() does not set by default. And you can set the header using the headers argument like so where the array key is referer (note that it’s not double “r” as in “referrer”):

$response = wp_remote_get( esc_url_raw( $url ), array(
    'headers' => [ 'referer' => home_url() ],
) );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x