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

new(api_key:) click to toggle source

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

source_languages() click to toggle source

Retrieve all currently available source languages.

See also the [vendor documentation](www.deepl.com/docs-api/other-functions/listing-supported-languages/).

Returns a dictionary like: `{“DE” => “German”, …}`

# File lib/deepl_api.rb, line 82
def source_languages
  languages(type: "source")
end
target_languages() click to toggle source

Retrieve all currently available target languages.

See also the [vendor documentation](www.deepl.com/docs-api/other-functions/listing-supported-languages/).

Returns a dictionary like: `{“DE” => “German”, …}`

# File lib/deepl_api.rb, line 91
def target_languages
  languages(type: "target")
end
translate( source_language: nil, target_language:, split_sentences: nil, preserve_formatting: true, formality: Formality::DEFAULT, texts: ) click to toggle source

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](www.deepl.com/docs-api/translating-text/) for details.

Returns a list of dictionaries for the translated content:

“`ruby [

{
  "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
usage_information() click to toggle source

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](www.deepl.com/docs-api/other-functions/monitoring-usage/).

# 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

Private Instance Methods

api_call(url:, payload: {}) click to toggle source

Private method to perform the actual HTTP calls.

# File lib/deepl_api.rb, line 144
def api_call(url:, payload: {})
  res = Net::HTTP.post_form(URI(@api_base_url + url), { **payload, auth_key: @api_key })
  return JSON.parse(res.body) if res.instance_of? Net::HTTPOK
  if res.instance_of?(Net::HTTPUnauthorized) || res.instance_of?(Net::HTTPForbidden)
    raise DeeplAPI::Errors::DeeplAuthorizationError, "Authorization failed, is your API key correct?"
  end

  begin
    data = JSON.parse(res.body)
    if data["message"]
      raise DeeplAPI::Errors::DeeplServerError,
            "An error occurred while communicating with the DeepL server: '#{data["message"]}'."
    end
  rescue JSON::ParserError
    raise DeeplAPI::Errors::DeeplServerError, res.code
  end
  raise DeeplAPI::Errors::DeeplServerError, res.code
end
languages(type:) click to toggle source

Private method to make API calls for the language lists

# File lib/deepl_api.rb, line 164
def languages(type:)
  data = api_call(url: "/languages", payload: { type: type })
  raise(DeeplAPI::Errors::DeeplDesearializationError) if !data.length || !data[0].include?("language")

  result = {}
  data.each { |i| result[i["language"]] = i["name"] }
  result
end