最新のgoogle-api-php-client

まず、コマンドラインでphpのバージョンを確認します。

[vagrant@localhost api]$ php -v
PHP 5.6.27 (cli) (built: Oct 14 2016 14:06:54)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

gitも確認。

[vagrant@localhost api]$ git version
git version 2.2.1

githubにあるリポジトリをローカルにcloneします。

[vagrant@localhost api]$ git clone https://github.com/google/google-api-php-client.git
Cloning into 'google-api-php-client'...
remote: Counting objects: 10177, done.
remote: Compressing objects: 100% (16/16), done.
remote: Total 10177 (delta 3), reused 8 (delta 2), pack-reused 10158
Receiving objects: 100% (10177/10177), 6.98 MiB | 1.51 MiB/s, done.
Resolving deltas: 100% (6953/6953), done.
Checking connectivity... done.

入りました。

では、試しに、examplesをサーバーで見てみましょう。

[vagrant@localhost google-api-php-client]$ php -S 192.168.33.10:8000
PHP 5.6.27 Development Server started at Mon Jan 29 16:12:27 2018
Listening on http://192.168.33.10:8000
Document root is /home/vagrant/api/google-api-php-client
Press Ctrl-C to quit.
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59098 [200]: /examples/
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59099 [200]: /examples/styles/style.css
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59101 [404]: /favicon.ico - No such file   or directory
[Mon Jan 29 16:12:47 2018] 192.168.33.1:59100 Invalid request (Unexpected EOF)

foreach loop sample2

We have an associative array that stores name and yield.

<?php
$yield = array(
	"レカム"=> "16,776,900",
	"JALCOホールディングス"=>"15,380,900",
	"明豊エンタープライズ"=>"12,639,200",
	"石垣食品"=>"5,372,100",
	"ネクストウェア"=>"5,073,400"
);

foreach( $yield as $key => $value){
	echo "銘柄: $key, 出来高: $value<br>";
}
?>

foreach文

指定した配列に関してループ処理を実行。各ループ時には、現在の要素の値が変数$valueに代入され、配列ポインタが1つ進められる。

foreach文の使用例

foreach (配列 as value)
 ループ処理

サンプル

<?php
$a = array(
	1 => 1,
	2 => 4,
	3 => 9,
	4 => 16
);

foreach( $a as $value){
	echo $value."<br>\n";
}
?>

拡張構文
各ループで、要素の値が$valに、要素のキーが変数$valに代入される。

foreach(配列 as $key => $val)
 ループ処理;

サンプル

<?php
$body = array(
	"head" => "頭",
	"nose" => "鼻",
	"face" => "顔",
	"hand" => "手"
	);

foreach( $body as $key => $value){
	echo $key. ":" .$value."<br>\n";
}
?>

多次元配列の出力

<?php
$code = array(
	"Mothers"=> array(
		"ブライトパス・バイオ"=> "4594",
		"ジーエヌアイグループ"=> "2160",
		"アンジェス"=> "4563",
		"ナノキャリア"=> "4571"
		),
	"JASDAQ"=> array(
		"レカム"=> "3323",
		"JALCOホールディングス"=> "6625",
		"明豊エンタープライズ"=> "8917",
		"石垣食品"=> "2901"
		)
);

foreach( $code as $key1 => $val1){
	echo "--".$key1. "--<br>\n";

	foreach( $val1 as $key2 => $val2){
		echo $key2. ":" .$val2."<br>\n";
	}
}
?>

Google API Client Librariesとは?

API Client Libraries offers simple, flexible, powerful access to many Google APIs.

Setup
1. sign up Google account
2. create a project in the Google API Console
3. Install the library

google-api-php-client
https://github.com/google/google-api-php-client

Authentication and authorization
All API calls must use either simple or authorized access.
API Key: to authenticate your application, use API Key for your Google API Console.

Authorized API access(OAuth 2.0)
your application must be authenticated, the user must grant access for your application, and the user must be authenticated in order to grant that access.
scope: each api defines one or more scopes that declare a set of operations permitted.
Refresh and access tokens: when a user grants your application access, the OAuth 2.0 authorization server provides your application with refresh and access tokens.
Client ID and client secret: these strings uniquely identify your application and are used to acquire tokens.

Build the client object

$client = new Google_Client();
$client->setApplicationName("My Application")
$client->setDeveloperKey("My_SIMPLE_API_KEY")

Build the service object
services are called through queries to service specific objects. These are created by constructing the service object, and passing an instance of Google_Client to it.

$service = new Google_Service_Books($client);

Calling an API
each API provides resources and methods, usually in chain. These can be accessed from the service object in the form $service->resource->method(args). Most method require some arguments, then accept a final parameter of an array containing optional parameters.

$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoeau', $optParams);

Handling the result
There are two main types of response – items and collections of items. Each can be accessed either as an object or as an array.

foreach($results as $item){
	echo $item['volumeInfo']['title'], "<br />\n";
}

Google APIs Client Library for PHP

Google APIs Client Library for PHP
https://code.google.com/archive/p/google-api-php-client/downloads

最新版をダウンロードして、展開します。

[vagrant@localhost youtube]$ tar zxvf google-api-php-client-0.6.7.tar.gz
google-api-php-client/
google-api-php-client/NOTICE
google-api-php-client/README
google-api-php-client/test/
google-api-php-client/test/phpunit.xml
google-api-php-client/test/general/
google-api-php-client/test/general/OAuthHelper.php
google-api-php-client/test/general/CacheTest.php
google-api-php-client/test/general/GeneralTests.php
google-api-php-client/test/general/AuthTest.php
google-api-php-client/test/general/ServiceTest.php
google-api-php-client/test/general/ApiModelTest.php
google-api-php-client/test/general/IoTest.php
google-api-php-client/test/general/testdata/
google-api-php-client/test/general/testdata/test_public_key.pem
google-api-php-client/test/general/ApiClientTest.php
google-api-php-client/test/general/ApiOAuth2Test.php
google-api-php-client/test/general/ApiMediaFileUploadTest.php
google-api-php-client/test/general/ApiBatchRequestTest.php
google-api-php-client/test/general/RestTest.php
google-api-php-client/test/general/ApiCacheParserTest.php
google-api-php-client/test/tasks/
google-api-php-client/test/tasks/TasksTest.php
google-api-php-client/test/tasks/AllTasksTests.php
google-api-php-client/test/adsense/
google-api-php-client/test/adsense/AdSenseTest.php
google-api-php-client/test/AllTests.php
google-api-php-client/test/README
google-api-php-client/test/plus/
google-api-php-client/test/plus/PlusTest.php
google-api-php-client/test/BaseTest.php
google-api-php-client/test/pagespeed/
google-api-php-client/test/pagespeed/PageSpeedTest.php
google-api-php-client/test/pagespeed/AllPageSpeedTests.php
google-api-php-client/test/urlshortener/
google-api-php-client/test/urlshortener/AllUrlShortenerTests.php
google-api-php-client/test/urlshortener/UrlShortenerTests.php
google-api-php-client/src/
google-api-php-client/src/cache/
google-api-php-client/src/cache/Google_MemcacheCache.php
google-api-php-client/src/cache/Google_Cache.php
google-api-php-client/src/cache/Google_FileCache.php
google-api-php-client/src/cache/Google_ApcCache.php
google-api-php-client/src/Google_Client.php
google-api-php-client/src/config.php
google-api-php-client/src/auth/
google-api-php-client/src/auth/Google_LoginTicket.php
google-api-php-client/src/auth/Google_Auth.php
google-api-php-client/src/auth/Google_Verifier.php
google-api-php-client/src/auth/Google_PemVerifier.php
google-api-php-client/src/auth/Google_AssertionCredentials.php
google-api-php-client/src/auth/Google_OAuth2.php
google-api-php-client/src/auth/Google_AuthNone.php
google-api-php-client/src/auth/Google_Signer.php
google-api-php-client/src/auth/Google_P12Signer.php
google-api-php-client/src/io/
google-api-php-client/src/io/Google_HttpStreamIO.php
google-api-php-client/src/io/Google_CacheParser.php
google-api-php-client/src/io/Google_HttpRequest.php
google-api-php-client/src/io/cacerts.pem
google-api-php-client/src/io/Google_CurlIO.php
google-api-php-client/src/io/Google_REST.php
google-api-php-client/src/io/Google_IO.php
google-api-php-client/src/service/
google-api-php-client/src/service/Google_ServiceResource.php
google-api-php-client/src/service/Google_Service.php
google-api-php-client/src/service/Google_MediaFileUpload.php
google-api-php-client/src/service/Google_Utils.php
google-api-php-client/src/service/Google_BatchRequest.php
google-api-php-client/src/service/Google_Model.php
google-api-php-client/src/contrib/
google-api-php-client/src/contrib/Google_SQLAdminService.php
google-api-php-client/src/contrib/Google_PlusService.php
google-api-php-client/src/contrib/Google_UrlshortenerService.php
google-api-php-client/src/contrib/Google_FreebaseService.php
google-api-php-client/src/contrib/Google_DatastoreService.php
google-api-php-client/src/contrib/Google_AdExchangeSellerService.php
google-api-php-client/src/contrib/Google_ReportsService.php
google-api-php-client/src/contrib/Google_StorageService.php
google-api-php-client/src/contrib/Google_SiteVerificationService.php
google-api-php-client/src/contrib/Google_TasksService.php
google-api-php-client/src/contrib/Google_CustomsearchService.php
google-api-php-client/src/contrib/Google_TranslateService.php
google-api-php-client/src/contrib/Google_CalendarService.php
google-api-php-client/src/contrib/Google_ShoppingService.php
google-api-php-client/src/contrib/Google_AndroidpublisherService.php
google-api-php-client/src/contrib/Google_GroupssettingsService.php
google-api-php-client/src/contrib/Google_PredictionService.php
google-api-php-client/src/contrib/Google_FusiontablesService.php
google-api-php-client/src/contrib/Google_MirrorService.php
google-api-php-client/src/contrib/Google_AdSenseService.php
google-api-php-client/src/contrib/Google_AppstateService.php
google-api-php-client/src/contrib/Google_CoordinateService.php
google-api-php-client/src/contrib/Google_DriveService.php
google-api-php-client/src/contrib/Google_AnalyticsService.php
google-api-php-client/src/contrib/Google_DfareportingService.php
google-api-php-client/src/contrib/Google_GamesService.php
google-api-php-client/src/contrib/Google_BooksService.php
google-api-php-client/src/contrib/Google_PagespeedonlineService.php
google-api-php-client/src/contrib/Google_AdsensehostService.php
google-api-php-client/src/contrib/Google_OrkutService.php
google-api-php-client/src/contrib/Google_AdexchangebuyerService.php
google-api-php-client/src/contrib/Google_DirectoryService.php
google-api-php-client/src/contrib/Google_YouTubeService.php
google-api-php-client/src/contrib/Google_LicensingService.php
google-api-php-client/src/contrib/Google_CivicInfoService.php
google-api-php-client/src/contrib/Google_BigqueryService.php
google-api-php-client/src/contrib/Google_ResellerService.php
google-api-php-client/src/contrib/Google_Oauth2Service.php
google-api-php-client/src/contrib/Google_ModeratorService.php
google-api-php-client/src/contrib/Google_ComputeService.php
google-api-php-client/src/contrib/Google_TaskqueueService.php
google-api-php-client/src/contrib/Google_GamesManagementService.php
google-api-php-client/src/contrib/Google_GanService.php
google-api-php-client/src/contrib/Google_BloggerService.php
google-api-php-client/src/contrib/Google_PlusDomainsService.php
google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php
google-api-php-client/src/contrib/Google_WebfontsService.php
google-api-php-client/src/contrib/Google_AuditService.php
google-api-php-client/src/external/
google-api-php-client/src/external/URITemplateParser.php
google-api-php-client/LICENSE
google-api-php-client/examples/
google-api-php-client/examples/analytics/
google-api-php-client/examples/analytics/simple.php
google-api-php-client/examples/analytics/demo/
google-api-php-client/examples/analytics/demo/managementApiReference.php
google-api-php-client/examples/analytics/demo/index.php
google-api-php-client/examples/analytics/demo/helloAnalyticsApi.php
google-api-php-client/examples/analytics/demo/storage.php
google-api-php-client/examples/analytics/demo/authHelper.php
google-api-php-client/examples/analytics/demo/coreReportingApiReference.php
google-api-php-client/examples/tasks/
google-api-php-client/examples/tasks/index.php
google-api-php-client/examples/tasks/css/
google-api-php-client/examples/tasks/css/style.css
google-api-php-client/examples/customSearch/
google-api-php-client/examples/customSearch/index.php
google-api-php-client/examples/userinfo/
google-api-php-client/examples/userinfo/index.php
google-api-php-client/examples/calendar/
google-api-php-client/examples/calendar/simple.php
google-api-php-client/examples/webfonts/
google-api-php-client/examples/webfonts/simple.php
google-api-php-client/examples/batch.php
google-api-php-client/examples/translate/
google-api-php-client/examples/translate/simple.php
google-api-php-client/examples/adsense/
google-api-php-client/examples/adsense/index.php
google-api-php-client/examples/adsense/style.css
google-api-php-client/examples/adsense/htmlHelper.php
google-api-php-client/examples/adsense/examples/
google-api-php-client/examples/adsense/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adsense/examples/GetAllMetrics.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannels.php
google-api-php-client/examples/adsense/examples/GetAllSavedAdStyles.php
google-api-php-client/examples/adsense/examples/GenerateGeoChart.php
google-api-php-client/examples/adsense/examples/GenerateLineChart.php
google-api-php-client/examples/adsense/examples/GetAllAccounts.php
google-api-php-client/examples/adsense/examples/GetAllSavedReports.php
google-api-php-client/examples/adsense/examples/GetAllAdUnits.php
google-api-php-client/examples/adsense/examples/GetAllUrlChannels.php
google-api-php-client/examples/adsense/examples/GetAllAlerts.php
google-api-php-client/examples/adsense/examples/GenerateTableChart.php
google-api-php-client/examples/adsense/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adsense/examples/GenerateSavedReport.php
google-api-php-client/examples/adsense/examples/GeneratePieChart.php
google-api-php-client/examples/adsense/examples/GetAllDimensions.php
google-api-php-client/examples/adsense/examples/GenerateColumnChart.php
google-api-php-client/examples/adsense/examples/HandleAccountErrors.php
google-api-php-client/examples/adsense/examples/GenerateReport.php
google-api-php-client/examples/adsense/examples/GetAllAdClients.php
google-api-php-client/examples/adsense/examples/GetAccountTree.php
google-api-php-client/examples/adsense/examples/GetAllAdClientsForAccount.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adsense/BaseExample.php
google-api-php-client/examples/adsense/AdSenseAuth.php
google-api-php-client/examples/affiliateNetwork/
google-api-php-client/examples/affiliateNetwork/index.php
google-api-php-client/examples/books/
google-api-php-client/examples/books/index.php
google-api-php-client/examples/books/simple.php
google-api-php-client/examples/books/interface.html
google-api-php-client/examples/books/books_browser.css
google-api-php-client/examples/moments/
google-api-php-client/examples/moments/simple.php
google-api-php-client/examples/adexchangebuyer/
google-api-php-client/examples/adexchangebuyer/index.php
google-api-php-client/examples/adexchangebuyer/style.css
google-api-php-client/examples/adexchangebuyer/htmlHelper.php
google-api-php-client/examples/adexchangebuyer/examples/
google-api-php-client/examples/adexchangebuyer/examples/UpdateAccount.php
google-api-php-client/examples/adexchangebuyer/examples/GetAllAccounts.php
google-api-php-client/examples/adexchangebuyer/examples/GetDirectDeals.php
google-api-php-client/examples/adexchangebuyer/examples/SubmitCreative.php
google-api-php-client/examples/adexchangebuyer/examples/GetCreative.php
google-api-php-client/examples/adexchangebuyer/BaseExample.php
google-api-php-client/examples/plus/
google-api-php-client/examples/plus/index.php
google-api-php-client/examples/plus/simple.php
google-api-php-client/examples/plus/style.css
google-api-php-client/examples/plus/README
google-api-php-client/examples/siteVerification/
google-api-php-client/examples/siteVerification/simple.php
google-api-php-client/examples/adsensehost/
google-api-php-client/examples/adsensehost/index.php
google-api-php-client/examples/adsensehost/style.css
google-api-php-client/examples/adsensehost/htmlHelper.php
google-api-php-client/examples/adsensehost/examples/
google-api-php-client/examples/adsensehost/examples/GenerateReportForHost.php
google-api-php-client/examples/adsensehost/examples/AddUrlChannelToHost.php
google-api-php-client/examples/adsensehost/examples/AddCustomChannelToHost.php
google-api-php-client/examples/adsensehost/examples/GenerateReportForPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/VerifyAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAllAdUnitsForPublisher.php
google-api-php-client/examples/adsensehost/examples/StartAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAccountDataForExistingPublisher.php
google-api-php-client/examples/adsensehost/examples/GetAllUrlChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllCustomChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForPublisher.php
google-api-php-client/examples/adsensehost/examples/DeleteUrlChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/AddAdUnitToPublisher.php
google-api-php-client/examples/adsensehost/BaseExample.php
google-api-php-client/examples/adsensehost/AdSenseHostAuth.php
google-api-php-client/examples/shopping/
google-api-php-client/examples/shopping/simple.php
google-api-php-client/examples/adexchangeseller/
google-api-php-client/examples/adexchangeseller/AdExchangeSellerAuth.php
google-api-php-client/examples/adexchangeseller/index.php
google-api-php-client/examples/adexchangeseller/style.css
google-api-php-client/examples/adexchangeseller/htmlHelper.php
google-api-php-client/examples/adexchangeseller/examples/
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adexchangeseller/examples/GetAllMetrics.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllPreferredDeals.php
google-api-php-client/examples/adexchangeseller/examples/GetAllSavedReports.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnits.php
google-api-php-client/examples/adexchangeseller/examples/GetAllUrlChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAlerts.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adexchangeseller/examples/GenerateSavedReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllDimensions.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdClients.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adexchangeseller/BaseExample.php
google-api-php-client/examples/prediction/
google-api-php-client/examples/prediction/serviceAccount.php
google-api-php-client/examples/prediction/index.php
google-api-php-client/examples/prediction/style.css
google-api-php-client/examples/prediction/README
google-api-php-client/examples/youtube/
google-api-php-client/examples/youtube/my_uploads.php
google-api-php-client/examples/youtube/search.php
google-api-php-client/examples/pagespeed/
google-api-php-client/examples/pagespeed/index.php
google-api-php-client/examples/pagespeed/style.css
google-api-php-client/examples/urlshortener/
google-api-php-client/examples/urlshortener/index.php
google-api-php-client/examples/urlshortener/style.css
google-api-php-client/examples/contacts/
google-api-php-client/examples/contacts/simple.php
google-api-php-client/examples/apps/
google-api-php-client/examples/apps/index.php
[vagrant@localhost youtube]$ ls
google-api-php-client  google-api-php-client-0.6.7.tar.gz  index.php

ruby api sample

require 'google/api_client'
require 'google/api_client/client_secrets'
require 'json'
require 'launchy'
require 'thin'

RESPONSE_HTML = <<stop
<html>
	<head>
		<title>OAuth 2 Flow Complete</title>
	</head>
	<body>
			You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.
	</body>
</html>
stop

FILE_POSTFIX = '-oauth2.json'

class CommandLineOAuthHelper

	def initialize(scope)
		credentials = Google::APIClient::ClientSecrets.load
		@authorization = Signet::OAuth2::Client.new(
				:authorization_uri => credentials.authorization_uri,
				:token_credential_uri => credentials.token_credential_uri,
				:client_id => credentials.cliend_id,
				:client_secret => credentials.client_secret,
				:redirect_uri => credentials.redirect_uris.first,
				:scope => scope
		)
	end

	def authorize
		credentialsFile = $0 + FILE_POSTFIX

		if File.exist? candentialsFile
			File.open(credentialsFile, 'r') do |file|
				credentials = JSON.load(file)
				@authorization.access_token = credentials['access_token']
				@authorization.client_id = credentials['client_id']
				@authorization.client_secret = credentials['client_secret']
				@authorization.refresh_token = credentials['refresh_token']
				@authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).credentialsFile
				if @authorization.expired?
					@authorization.fetch_access_token!
					save(credentialsFile)
				end
			end
		else
			auth = @authorization
			url = @authorization.authorization_uri().to_s
			server = Thin::Server.new('0.0.0.0', 8080) do
				run lambda { |env|
					req = Rack::Request.new(env)
					auth.code = req['code']
					auth.fetch_access_token!
					server.stop()
					[200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]
				}
		end

		Launchy.open(url)
		server.start()

		save(credentialsFile)
	end

	return @authorization
	end

	def save(credentialsFile)
		File.open(credentialsFile, 'w', 0600) do |file|
			json = JSON.dump({
				:access_token => @authorization.access_token,
				:client_id => @authorization.client_id,
				:client_secret => @authorization.client_secret,
				:refresh_token => @authorization.refresh_token,
				:token_expiry => @authorization.expires_at
				})
				file.write(json)
		end
	end
end

python api sample2

import os
import urllib
import webapp2
import jinja2

from apiclient.discovery import build
from optparse import OptionParser

JINJA_ENVIRONMENT = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
	extensions=['jinja2.ext.autoescape'])

DEVELPOER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

class MainHandler(webapp2.RequestHandler):

	def get(self):
		if DEVELOPER_KEY == "REPLACE_ME":
			self.response.write("""You must set up a project and get an API key
									to run this project. Please visit 
									<landing page> to do so."""
		else:
			youtube = build(
				YOUTUBE_API_SERVICE_NAME,
				YOUTUBE_API_VERSION,
				developerKey=DEVELOPER_KEY)
			search_response = youtube.search().list(
				q="Hello",
				part="id,snippet",
				maxResults=5
				).execute()

				videos = []
				channels = []
				playlists = []

				for search_result in search_response.get("items", []):
					if search_result["id"]["kind"] == "youtube#video":
						videos.append("%s (%s)" % (search_result["snippet"]["title"],
							search_result["id"]["videoId"]))
					elif search_result["id"]["kind"] == "youtube#channel":
						channels.append("%s (%s)" % (search_result["snippet"]["title"],
							search_result["id"]["channelId"]))
					elif search_result["id"]["kind"] == "youtube#playlist":
						playlists.append("%s (%s)" % (search_result["snippet"]["title"],
							search_result["id"]["playlistId"]))

				template_values = {
					'videos': videos,
					'channels': channels,
					'playlists': playlists
				}

				self.response.headers['Content-type'] = 'text/plain'
				template = JINJA_ENVIRONMENT.get_template('index.html')
				self.response.write(template.render(template_values))				

			app = webapp2.WSGIApplication([
				('/.*', MainHandler)
				], debug=True)

python api sample

#!/usr/bin/python

import httplib2
import os
import sys

from applicient.discovery import build
from applicient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

CLIENT_SECRETS_FILE = "client_secret.json"

YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

MISSING_CLIENT_SECRET_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

		%S

with information from the Developers Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please vist:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
	CLIENT_SECRETS_FILE))

def get_authenticated_service(args):
	flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
		scope=YOUTUBE_READ_WRITE_SCOPE,
		message=MISSING_CLIENT_SECRETS_MESSAGE)

	storage = Storage("%s-oauth2.json" % sys.argv[0])
	credentials = storage.get()

	if credentials is None or credentials.invalid:
		credentials = run_flow(flow, storage, args)

	return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
		http=credentials.authorize(httplib2.Http()))

	def post_bulletin(youtube, args):
		body = dict(
			snippet=dict(
					description=args.message
				)
			)

			if args.vide_id:
				body["contentDetails"] = dict(
					bulletin=dict(
						resourceID=dict(
							kind="youtube#video",
							videoId=args.video_id
							)
						)
					)

			if args.playlist_id:
				body["contentDetails"] = dict(
					bulletin=dict(
						resourceId=dict(
						kind="youtube#playlist",
						playlistId=args.playlist_id
						)
					)
				)

			youtube.activities().insert(
				part=",".join(body.keys()),
				body=body
				).execute()

		if __name__ == "__main__":
			argparser.add_argument("--message", requred=True,
				help="Text of message to post.")
			argparser.add_argument("--video-id",
				help="Optional ID of video to post.")
			argparser.add_argument("--playlist-id",
				help="Optional ID of playllist to post.")
			args = argparser.parse_args()

			if args.video_id and args.playlist_id:
				exit("You cannnot post a video and a playlist at the same time.")

			youtube = get_authenticated_service(args)
			try:
				post_bulletin(youtube, args)
			except HttpError, e:
				print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
			else:
				print "The bulletin was posted to your channel."

PHP API sample

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();

$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
	FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new Google_Service_Youtube($client);

if (isset($_GET['code'])){
	if (strval($_SESSION['state']) !== strval($_GET['state'])){
		die('The session state did not match.');
	}

	$client->authenticate($_GET['code']);
	$_SESSION['token'] = $client->getAccessToken();
	header('Location:' . $redirect);
}

if (isset($_SESSION['token'])) {
	$client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()){
	try{

	$videoId = "VIDEO_ID";

	$imagePath = "/path/to/file.png";

	$chunkSizeBytes = 1 * 1024 * 1024;

	$client->setDefer(true);

	$setRequest = $youtube->thumbnails->set($videoId);

	$media = new Google_Http_MediaFileUpload(
		$client,
		$setRequest,
		'image/png',
		null,
		true,
		$chunkSizeBytes
		);
		$media->setFileSize(filesize($imagePath));

		$status = false;
		$handle = fopen($imagePath, "rb");
		while (!$status && !feof($handle)){
			$chunk = fread($handle, $chunkSizeBytes);
			$status = $media->nextChunk($chunk);
		}

		fclose($handle);

		$client->setDefer(false);

		$thumbnailUrl = $status['items'][0]['default']['url'];
		$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
		$htmlBody .= sprintf('<li>%s (%s)</li>',
			$videoId,
			$thumbnailUrl);
		$htmlBody .= sprintf('<img src="$s">', $thumbnailUrl);
		$htmlBody .= '</ul>';

	} catch(Google_Service_Exception Se){
		$htmlBody .= sprintf('<p>A.service error occured: <code>%s</code></p>',
			htmlspecialchars($e->getMessage()));
	} catch (Google_Exception $e){
		$htmlBody .=sprintf('<p>An client error occurred: <code>%s</code></p>',
			htmlspecialchars($e->getMessage()));
	}

	$_SESSION['token'] = $client->getAccessToken();
} ese{
	$state = mt_rand();
	$clilent->setState($state);
	$_SESSION['state'] = $state;

	$authUrl = $client->createAuthUrl();
	$htmlBody = <<<END
	<h3>Authorization Requred </h3>
	<p>You need to <a href="$authUrl">authorize acceess</a>before proceeding.</p>
	END;
}
?>

<!doctype html>
<html>
<head>
<title>Claim Uploaded </title>
</head>
<body>
		<?=$htmlBody?>
</body>
</html>