class DeeplAPI::DeepL
The main API entry point representing a DeepL
developer account with an associated API key.
Use this to create a new DeepL
API client instance where multiple function calls can be performed. A valid api_key
is required.
Should you ever need to use more than one DeepL
account in our program, then you can create one instance for each account / API key.
Error Handling¶ ↑
These methods may throw exceptions from DeeplAPI::Errors
and Net::HTTP
.
Public Class Methods
Create an instance by providing a valid API key.
# File lib/deepl_api.rb, line 55 def initialize(api_key:) @api_key = api_key.to_s @api_base_url = @api_key[-3, 3].eql?(":fx") ? "https://api-free.deepl.com/v2" : "https://api.deepl.com/v2" return unless @api_key.empty? raise DeeplAPI::Errors::DeeplAuthorizationError, "No API key provided." end
Public Instance Methods
Retrieve all currently available source languages.
See also the vendor documentation.
Returns a dictionary like: {"DE" => "German", ...}
# File lib/deepl_api.rb, line 82 def source_languages languages(type: "source") end
Retrieve all currently available target languages.
See also the vendor documentation.
Returns a dictionary like: {"DE" => "German", ...}
# File lib/deepl_api.rb, line 91 def target_languages languages(type: "target") end
Translate one or more text chunks at once. You can pass in optional translation options if you need non-default behaviour.
Please see the parameter documentation and the vendor documentation for details.
Returns a list of dictionaries for the translated content:
[ { "detected_source_language" => "DE", "text" => "Yes. No.", }, ... ]
# File lib/deepl_api.rb, line 114 def translate( source_language: nil, target_language:, split_sentences: nil, preserve_formatting: true, formality: Formality::DEFAULT, texts: ) # rubocop:enable Metrics/ParameterLists, Style/KeywordParametersOrder payload = { target_lang: target_language, text: texts } payload[:source_lang] = source_language unless source_language.nil? payload[:split_sentences] = split_sentences unless split_sentences.nil? payload[:preserve_formatting] = preserve_formatting unless preserve_formatting.nil? payload[:formality] = formality unless formality.nil? data = api_call(url: "/translate", payload: payload) raise DeeplAPI::Errors::DeeplDeserializationError unless data.include?("translations") data["translations"] end
Retrieve information about API usage & limits. This can also be used to verify an API key without consuming translation contingent.
Returns a DeeplAPI::UsageInformation
object.
See also the vendor documentation.
# File lib/deepl_api.rb, line 69 def usage_information data = api_call(url: "/usage") UsageInformation.new( character_count: data["character_count"], character_limit: data["character_limit"] ) end