Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Cloud Natural Language API をPerlで使う
use strict;
use warnings;
use utf8;
use JSON;
use HTTP::Tiny;
# Goolge Cloud Natural Language API analyzeSentiment
my $GOOGLE_API_URL
= 'https://language.googleapis.com/v1/documents:analyzeSentiment';
# $ gcloud auth application-default print-access-token
my $GOOGLE_API_KEY = 'YOUR_GOOGLE_API_KEY';
# 標準モジュールのHTTP::Tinyを利用
my $http = HTTP::Tiny->new();
# リクエストに必要なHTTPヘッダーを組み立て
my $header = {
headers => {
'Authorization' => 'Bearer ' . $GOOGLE_API_KEY,
'Content-Type' => 'application/json; charset=utf-8',
},
content => encode_json {
document => {
type => 'PLAIN_TEXT',
language => 'ja',
content => 'sironekotoroは幸せ',
},
},
};
# ヘッダー上記で組み立てたヘッダーを元にPOSTで問い合わせ
my $response = $http->request( 'POST', $GOOGLE_API_URL, $header );
# APIのレスポンスを表示する
# ここはHTTP::TinyのUSAGEそのまま
print "$response->{status} $response->{reason}\n";
die "Failed!\n" unless $response->{success};
while ( my ( $k, $v ) = each %{ $response->{headers} } ) {
for ( ref $v eq 'ARRAY' ? @$v : $v ) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
# 200 OK
# accept-ranges: none
# transfer-encoding: chunked
# x-content-type-options: nosniff
# x-xss-protection: 0
# date: Mon, 26 Aug 2019 04:06:34 GMT
# cache-control: private
# vary: X-Origin
# vary: Referer
# vary: Origin,Accept-Encoding
# server: ESF
# content-type: application/json; charset=UTF-8
# x-frame-options: SAMEORIGIN
# alt-svc: quic=":443"; ma=2592000; v="46,43,39"
# {
# "documentSentiment": {
# "magnitude": 0.8,
# "score": 0.8
# },
# "language": "ja",
# "sentences": [
# {
# "text": {
# "content": "sironekotoroは幸せ",
# "beginOffset": -1
# },
# "sentiment": {
# "magnitude": 0.8,
# "score": 0.8
# }
# }
# ]
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.