项目作者: pscott-au

项目描述 :
Perl WebService::GoogleAPI::Client Module
高级语言: Perl
项目地址: git://github.com/pscott-au/WebService-GoogleAPI-Client.git
创建时间: 2018-10-17T11:13:36Z
项目社区:https://github.com/pscott-au/WebService-GoogleAPI-Client

开源协议:Other

下载


NAME

WebService::GoogleAPI::Client - Perl Google API Services OAUTH Client.

Build Status
Coverage Status
CPAN Version
Kwalitee Score

Perl Google APIs Client Library

NAME

WebService::GoogleAPI::Client - Perl Google API Services OAUTH Client.

VERSION

version 0.21

SYNOPSIS

Provides client access to Google API V.1 Service End-Points using a user-agent that handles OAUTH2 authentication and access control and provides helpers to cache API Discovery specifications.

This module may look ‘heavy’ and that’s because it includes a lot of extra tools to streamline your exploration of Google API End-Points. In a production environment there will be options to trim down your implementation if this is required.

The guiding principal is to minimise the conceptual load when using the Client agent for users who want to make calls directly, but also make available functions to help explore unfamiliar API endpoints by offering optional validation etc against the latest published Google API Discovery specifications.

NB: To create or modify an authorization configuration file for a Goole Project with scope and user tokens in current folder run goauth CLI tool to interactively create the JSON configuration and launch a local HTTP server to acquire authenticated access permissions with a Google email account.

goauth screen capture

See perldoc goauth for more detail.

  1. use WebService::GoogleAPI::Client;
  2. use Data::Dumper;
  3. ## assumes gapi.json configuration in working directory with scoped project and user authorization
  4. my $gapi_client = WebService::GoogleAPI::Client->new( debug => 1, gapi_json => 'gapi.json', user=> 'peter@pscott.com.au' );
  5. ## Completely manually constructed API End-Point Request to obtain Perl Data Structure converted from JSON response.
  6. my $res = $gapi_client->api_query(
  7. method => 'get',
  8. path => 'https://www.googleapis.com/calendar/users/me/calendarList',
  9. )->json;

INSTALLATION

From Repository Source Root Using Dist::Zilla

The code in this repository uses Dist::Zilla Build System to assist package building and creation of Tarball and CPAN distribution. Curiously the Github Repo describes itself as ‘scary tools for building CPAN distributions

  1. dzil listdeps | cpanm
  2. dzil build
  3. dzil test
  4. dzil install

Install from CPAN

cpanm WebService::GoogleAPI::Client

Windows Strawberry Perl Notes

At the time of writing I had issues installing Config::Json V1.5202 due to an issue with the tests. Until the patch is applied it is OK to force the install in cpan to get things working.

I was unable to get the Dist::Zilla packages installed under Windows but installing without the dzil build layer through cpanm or cpan should now work as of V0.13

TYPICAL USAGE QUICKSTART

PRE-REQUISITES

  • Requires a suitably configured Project in Google Admin Console with scopes and OAUTH Client
  • Requires a local project configuration file that can be generated with the included goauth CLI Tool (perldoc goauth for more detail )
  1. use strict;
  2. use warnings;
  3. use Data::Dumper;
  4. use feature 'say';
  5. use WebService::GoogleAPI::Client;
  6. my $gapi = WebService::GoogleAPI::Client->new(debug => 0);
  7. ## This idiom selects the first authorised user from gapi.json
  8. my $aref_token_emails = $gapi->auth_storage->storage->get_token_emails_from_storage;
  9. my $user = $aref_token_emails->[0];
  10. print "Running tests with default user email = $user\n";
  11. $gapi->user($user);
  12. ## Get all emails sent to $user newer than 1 day
  13. my $cl = $gapi->api_query({
  14. method => 'get',
  15. path => "https://www.googleapis.com/gmail/v1/users/me/messages?q=newer_than:1d;to:$user",
  16. });
  17. if ($cl->code eq '200') ## Mojo::Message::Response
  18. {
  19. foreach my $msg ( @{ $cl->json->{messages} } )
  20. {
  21. say Dumper $msg;
  22. }
  23. }

More Examples

See the examples folder for specific access examples.

  1. ## using dotted API Endpoint id to invoke helper validation and default value interpolations etc to send email to self
  2. use Email::Simple; ## RFC2822 formatted messages
  3. use MIME::Base64;
  4. my $my_email_address = 'peter@shotgundriver.com'
  5. my $raw_email_payload = encode_base64( Email::Simple->create( header => [To => $my_email_address,
  6. From => $my_email_address,
  7. Subject =>"Test email from '$my_email_address' ",],
  8. body => "This is the body of email to '$my_email_address'",
  9. )->as_string
  10. );
  11. $gapi_client->api_query(
  12. api_endpoint_id => 'gmail.users.messages.send',
  13. options => { raw => $raw_email_payload },
  14. );
  15. ## TEXT TO SPEECH EXAMPLE
  16. my $text_to_speech_request_options = {
  17. 'input' => {
  18. 'text' => 'Using the Web-Services-Google-Client Perl module, it is now a simple matter to access all of the Google API Resources in a consistent manner.'
  19. },
  20. 'voice' => {
  21. 'languageCode' => 'en-gb',
  22. 'name' => 'en-GB-Standard-A',
  23. 'ssmlGender' => 'FEMALE'
  24. },
  25. 'audioConfig' => {
  26. 'audioEncoding'=> 'MP3'
  27. }
  28. };
  29. ## Using this API requires authorised https://www.googleapis.com/auth/cloud-platform scope
  30. if ( 0 ) ## use a full manually constructed non validating standard user agent query builder approach ( includes auto O-Auth token handling )
  31. {
  32. $r = $gapi_client->api_query(
  33. method => 'POST',
  34. path => 'https://texttospeech.googleapis.com/v1/text:synthesize',
  35. options => $text_to_speech_request_options
  36. ) ;
  37. }
  38. else ## use the api end-point id and take full advantage of pre-submission validation etc
  39. {
  40. $r = $gapi_client->api_query(
  41. api_endpoint_id => 'texttospeech.text.synthesize',
  42. # method => 'POST', ## not required as determined from API SPEC
  43. # path => 'https://texttospeech.googleapis.com/v1/text:synthesize', ## not required as determined from API SPEC
  44. options => $text_to_speech_request_options
  45. ) ;
  46. ## NB - this approach will also autofill any defaults that aren't defined
  47. ## confirm that the user has the required scope before submitting to Google.
  48. ## confirms that all required fields are populated
  49. ## where an error is detected - result is a 418 code ( I'm a teapot ) with the body containing the error descriptions
  50. }
  51. if ( $r->is_success ) ## $r is a standard Mojo::Message::Response instance
  52. {
  53. my $returned_data = $r->json; ## convert from json to native hashref - result is a hashref with a key 'audioContent' containing synthesized audio in base64-encoded MP3 format
  54. my $decoded_mp3 = decode_base64( $returned_data->{audioContent} );
  55. my $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.mp3' );
  56. print $tmp $decoded_mp3;
  57. print "ffplay -nodisp -autoexit $tmp\n";
  58. `ffplay -nodisp -autoexit $tmp`;
  59. close($tmp);
  60. # ffplay -nodisp -autoexit ~/Downloads/en-GB-Standard-A.mp3
  61. }
  62. else
  63. {
  64. if ( $r->code eq '418' )
  65. {
  66. print qq{Cool - I'm a teapot - this was caught before sending the request through to Google \n};
  67. print $r->body;
  68. }
  69. else ## other error - should appear in warnings but can inspect $r for more detail
  70. {
  71. print Dumper $r;
  72. }
  73. }

KEY FEATURES

  • API Discovery with local caching using CHI File
  • OAUTH app credentials (client_id, client_secret, users access_token && refresh_token) storage stored in local gapi.json file
  • Automatic access_token refresh (if user has refresh_token) and saving refreshed token to storage
  • CLI tool (go_auth) with lightweight HTTP server to simplify config OAuth2 configuration, sccoping, authorization and obtaining access_ and refresh_ tokens

SEE ALSO

AUTHORS

COPYRIGHT AND LICENSE

This software is copyright (c) 2017-2018 by Peter Scott and others.

This is free software, licensed under:

  1. The Apache License, Version 2.0, January 2004