|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START apikeys_authenticate_api_key] |
| 16 | +require "googleauth" |
| 17 | +require "google/cloud/language/v1" |
| 18 | + |
| 19 | +def authenticate_with_api_key api_key_string |
| 20 | + # Authenticates with an API key for Google Language service. |
| 21 | + # |
| 22 | + # TODO(Developer): Uncomment the following line and set the value before running this sample. |
| 23 | + # |
| 24 | + # api_key_string = "mykey12345" |
| 25 | + # |
| 26 | + # Note: You can also set the API key via environment variable: |
| 27 | + # export GOOGLE_API_KEY=your-api-key |
| 28 | + # and use Google::Auth::APIKeyCredentials.from_env method to load it. |
| 29 | + # Example: |
| 30 | + # credentials = Google::Auth::APIKeyCredentials.from_env |
| 31 | + # if credentials.nil? |
| 32 | + # puts "No API key found in environment" |
| 33 | + # exit |
| 34 | + # end |
| 35 | + |
| 36 | + # Initialize API key credentials using the class factory method |
| 37 | + credentials = Google::Auth::APIKeyCredentials.make_creds api_key: api_key_string |
| 38 | + |
| 39 | + # Initialize the Language Service client with the API key credentials |
| 40 | + client = Google::Cloud::Language::V1::LanguageService::Client.new do |config| |
| 41 | + config.credentials = credentials |
| 42 | + end |
| 43 | + |
| 44 | + # Create a document to analyze |
| 45 | + text = "Hello, world!" |
| 46 | + document = { |
| 47 | + content: text, |
| 48 | + type: :PLAIN_TEXT |
| 49 | + } |
| 50 | + |
| 51 | + # Make a request to analyze the sentiment of the text |
| 52 | + sentiment = client.analyze_sentiment(document: document).document_sentiment |
| 53 | + |
| 54 | + puts "Text: #{text}" |
| 55 | + puts "Sentiment: #{sentiment.score}, #{sentiment.magnitude}" |
| 56 | + puts "Successfully authenticated using the API key" |
| 57 | +end |
| 58 | +# [END apikeys_authenticate_api_key] |
| 59 | + |
| 60 | +if $PROGRAM_NAME == __FILE__ |
| 61 | + api_key = ARGV[0] |
| 62 | + if api_key.nil? || api_key.empty? |
| 63 | + puts "Usage: ruby #{__FILE__} api-key" |
| 64 | + exit |
| 65 | + end |
| 66 | + authenticate_with_api_key api_key |
| 67 | +end |
0 commit comments