3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SalesforceからCloud Natural Language APIにアクセス

3
Posted at

SalesforceからGCPのサービスにアクセスします。
メールの本文を解析したかったのでCloud Natural Language APIをAPEXから利用する場合の設定です。

GCP側の設定

プロジェクトの作成

プロジェクトを作ります。
この辺を参照に。
お支払い情報が必要になると思いますが、素直に入れるしかないです。

APIキーの作成

Cloud Natural Language APIはOAuthなどの認証情報が必要なくAPIキーさえ指定してやれば利用できます。
APIキーはプロジェクトの「APIとサービス」にある「認証情報」から遷移した画面で作れます。
image.png
APIキーを選択して必要な項目を入力しますとキーを作成します。
image.png

salesforce側の設定

指定ログイン

エンドポイントは必要になるので指定ログインを作成します。
ハードコートすれば必要ないですが、、、
image.png
表示ラベルと名前は好きなものを。
URLは利用したいAPIのエンドポイントを。

APEX

詳しい説明は省きます。
コールアウトでNatural Language APIにアクセスさせています。
req.setEndpointで「指定ログイン」を指定したうえでパラメータ(kye)に"APIキー"を渡しています。
後はヘッダーを設定したりPOSTで送るのでBodyとしてJSONを組み立てています。

public without sharing class MailBodyParse {
    @AuraEnabled
    public static String parse( String body ) {

        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:GoogleML?key=[ここは作ったAPIキーを指定するんです]');
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json; charset=UTF-8 ');
        //JSON作るよん
        JSONGenerator gen = JSON.createGenerator(false);
        gen.writeStartObject();
        gen.writeStringField('encodingType', 'UTF8');
        gen.writeFieldName('document');
        gen.writeStartObject();
        gen.writeStringField('type', 'PLAIN_TEXT' );
        gen.writeStringField('content', body );
        gen.writeEndObject();
        gen.writeEndObject();
        //bodyを設定だよ
        req.setBody(gen.getAsString());
        Http http = new Http();
        HTTPResponse res = http.send(req);
        return res.getBody();
    }
}

実行すればJSONがレスポンスとして返ってきます。

終わりに

エンティティ解析しか使ってませんがなかなかにいい結果が返ってきました。
ちなみに月で5,000回までは無料で使えますが調子に乗って使うと課金が始まるです。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?