diff options
| author | Adam Russell <ac.russell@live.com> | 2019-07-21 15:24:05 -0400 |
|---|---|---|
| committer | Adam Russell <ac.russell@live.com> | 2019-07-21 15:24:05 -0400 |
| commit | 44866277df96a5f0ec320581a0cef3d21c3a39cb (patch) | |
| tree | 946d62dbbe817cbdfc85d9b7fd8c8e0d0c488afb | |
| parent | 2a16112bdf6da59fdc5eb0333e99083e549e0dbf (diff) | |
| download | perlweeklychallenge-club-44866277df96a5f0ec320581a0cef3d21c3a39cb.tar.gz perlweeklychallenge-club-44866277df96a5f0ec320581a0cef3d21c3a39cb.tar.bz2 perlweeklychallenge-club-44866277df96a5f0ec320581a0cef3d21c3a39cb.zip | |
adding code for optional API challenge
| -rw-r--r-- | challenge-017/adam-russell/perl5/ch-3.pl | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/challenge-017/adam-russell/perl5/ch-3.pl b/challenge-017/adam-russell/perl5/ch-3.pl new file mode 100644 index 0000000000..8cddfa5629 --- /dev/null +++ b/challenge-017/adam-russell/perl5/ch-3.pl @@ -0,0 +1,43 @@ +use strict; +use warnings; +## +# Write a script to use Bhagavad Gita API. +## +use JSON; +use REST::Client; +use constant ACCESS_TOKEN_URL => "https://bhagavadgita.io/auth/oauth/token"; +use constant API_URL => "https://bhagavadgita.io/api/v1/chapters/CHAPTER/verses/VERSE?access_token=ACCESS_TOKEN"; + +sub get_access_token{ + my($client) = @_; + my $body = "client_id=<CLIENT_ID>&client_secret=<CLIENT_SECRET>&grant_type=client_credentials&scope=verse%20chapter"; + $$client->addHeader("accept", "application/json"); + $$client->addHeader("content-type", "application/x-www-form-urlencoded"); + $$client->POST(ACCESS_TOKEN_URL, $body); + my $json = $$client->responseContent(); + $json = decode_json($json); + return $json->{access_token}; +} + +sub get_sloka{ + my($client, $chapter, $verse, $access_token) = @_; + my $url = API_URL; + $url =~ s/CHAPTER/$chapter/; + $url =~ s/VERSE/$verse/; + $url =~ s/ACCESS_TOKEN/$access_token/; + $$client->addHeader("accept", "application/json"); + $$client->addHeader("content-type", "application/x-www-form-urlencoded"); + $$client->GET($url); + my $json = $$client->responseContent(); + $json = decode_json($json); + return $json->{meaning}; +} + +MAIN:{ + my($chapter, $verse) = @ARGV[0 .. 1]; + my $client = new REST::Client; + my $access_token = get_access_token(\$client); + my $translation = get_sloka(\$client, $chapter, $verse, $access_token); + print "$translation\n"; +} + |
