godeeplapi

package module
v0.0.0-...-d006607 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 1, 2025 License: MIT Imports: 17 Imported by: 0

README

DeepL API Go Wrapper

A lightweight, easy-to-use Go wrapper for the DeepL Translation API that simplifies making translation requests.

Roadmap

  • Add examples for all methods
  • Make more tests

Features

  • Simple interface for translating text using DeepL's powerful machine translation
  • Support for all languages offered by DeepL
  • Easy configuration with environment variables
  • Comprehensive error handling
  • Fully tested implementation

Installation

go get github.com/AdolfZahid1e/godeeplapi

Prerequisites

  • Go 1.18 or higher
  • A DeepL API key (get one at DeepL API)

Usage

see examples

Supported Languages

The wrapper supports all languages provided by the DeepL API:

// Examples of target languages
models.TargetLanguage.German     // "DE"
models.TargetLanguage.EnglishUS  // "EN-US"
models.TargetLanguage.Spanish    // "ES"
models.TargetLanguage.Japanese   // "JA"
models.TargetLanguage.Russian    // "RU"
// ... and many more
Specifying Source Language (Optional)
request := translator.TranslationRequest{
    Text:       []string{"Hello, world!"},
    SourceLang: models.SourceLanguage.English,            // Optional: specify source language
    TargetLang: models.TargetLanguage.French,
}

API Reference

Translator

The main struct for handling translations.

type Translator struct {
    Config Config
}
TranslationRequest

The request structure sent to DeepL API.

type TranslationRequest struct {
    Text       []string `json:"text"`
    TargetLang string   `json:"target_lang"`
    SourceLang string   `json:"source_lang,omitempty"`
}

Error Handling

The library provides detailed error messages for common issues:

  • Missing API key
  • Network errors
  • API response errors
  • JSON parsing errors

Running Tests

go test -v ./tests

Make sure you have a .env file with your DeepL API key in the project root before running tests.

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest    = &APIError{StatusCode: 400, Message: "Bad Request"}
	ErrInvalidAuth   = &APIError{StatusCode: 401, Message: "Authentication failed"}
	ErrForbidden     = &APIError{StatusCode: 403, Message: "Forbidden. Insufficient access rights."}
	ErrNotFound      = &APIError{StatusCode: 404, Message: "The requested resource could not be found"}
	ErrRateLimit     = &APIError{StatusCode: 413, Message: "Rate limit exceeded"}
	ErrHeader        = &APIError{StatusCode: 415, Message: "The requested entries format specified in \"Accept\" is not supported."}
	Err429TooMany    = &APIError{StatusCode: 429, Message: "Too many requests. Please wait and resend request"}
	ErrQuotaExceeded = &APIError{StatusCode: 456, Message: "Quota exceeded"}
	ErrInternal      = &APIError{StatusCode: 500, Message: "Internal error"}
	ErrUnavailable   = &APIError{StatusCode: 503, Message: "Resource temporarily unavailable. Try again later."}
	Err529TooMany    = &APIError{StatusCode: 529, Message: "Too many requests. Please wait and resend request"}
)

Common error types for more specific handling

Functions

func NewDefaultLogger

func NewDefaultLogger() *defaultLogger

NewDefaultLogger Initialize the logger field with default values

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Details    string
}

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey string, isPro bool, opts ...ClientOption) *Client

NewClient creates a new DeepL API client for v2 API

func NewClientV3

func NewClientV3(apiKey string, isPro bool, opts ...ClientOption) *Client

NewClientV3 creates a new DeepL API client for v3 API

func (*Client) CreateGlossary

CreateGlossary creates a new glossary and returns info about it. Note: Use V3 client for this endpoint.

func (*Client) DeleteAllLangDictionaries

func (c *Client) DeleteAllLangDictionaries(ctx context.Context, id string, query models.GlossaryLangPair) error

DeleteAllLangDictionaries deletes the dictionary associated with the given language pair with the given glossary ID. Note: Use V3 client for this endpoint.

func (*Client) DeleteGlossary

func (c *Client) DeleteGlossary(ctx context.Context, id string) error

DeleteGlossary deletes the specified glossary. Note: Use V3 client for this endpoint.

func (*Client) EditGlossary

func (c *Client) EditGlossary(ctx context.Context, id string, req models.EditGlossaryRequest) (*models.Glossary, error)

EditGlossary edits glossary details, such as name or a dictionary for a source and target language. Note: Use V3 client for this endpoint.

func (*Client) GetGlossaryByID

func (c *Client) GetGlossaryByID(ctx context.Context, id string) (*models.Glossary, error)

GetGlossaryByID retrieves meta information for a single glossary, omitting the glossary entries. Note: Use V3 client for this endpoint.

func (*Client) GetGlossaryEntries

func (c *Client) GetGlossaryEntries(ctx context.Context, id string, query models.GlossaryLangPair) (*models.GlossaryEntriesResponse, error)

GetGlossaryEntries lists the entries of a single glossary in tsv format. Note: Use V3 client for this endpoint.

func (*Client) GetLanguages

func (c *Client) GetLanguages(ctx context.Context) ([]models.SupportedLanguage, error)

GetLanguages returns struct with all supported languages

func (*Client) GetUsageAndLimits

func (c *Client) GetUsageAndLimits(ctx context.Context) (*models.UsageAndLimitResponse, error)

GetUsageAndLimits returns characters translated in the current billing period and current maximum number of characters that can be translated per billing period.

func (*Client) ImproveText

func (c *Client) ImproveText(ctx context.Context, req models.RephraseRequest) (string, error)

ImproveText improves a text using the DeepL API

func (*Client) ListAllGlossaries

func (c *Client) ListAllGlossaries(ctx context.Context) (*models.AllGlossaryListResponse, error)

ListAllGlossaries returns all glossaries and their meta-information, but not the glossary entries. Note: Use V3 client for this endpoint.

func (*Client) ListLangPairsSupportedByGlossaries

func (c *Client) ListLangPairsSupportedByGlossaries(ctx context.Context) (*models.GlossaryListResponse, error)

ListLangPairsSupportedByGlossaries retrieves the list of language pairs supported by the glossary feature.

func (*Client) ReplaceOrCreateDictionaryInGlossary

func (c *Client) ReplaceOrCreateDictionaryInGlossary(ctx context.Context, id string, req models.Dictionary) (*models.EditOrCreateDictionaryInGlossaryResponse, error)

ReplaceOrCreateDictionaryInGlossary replaces or creates a dictionary in the glossary with the specified entries. Note: Use V3 client for this endpoint.

func (*Client) Translate

func (c *Client) Translate(ctx context.Context, request models.TranslationRequest) ([]string, error)

Translate text using the DeepL API

func (*Client) TranslateFile

func (c *Client) TranslateFile(ctx context.Context, req models.FileTranslationRequest, targetDir string) (string, error)

TranslateFile uploads a file for translation and monitors progress

type ClientOption

type ClientOption func(*Client)

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger sets a custom logger

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets a custom timeout for the HTTP client

type Config

type Config struct {
	IsPro         bool
	DeeplApiToken string
}

type Logger

type Logger interface {
	Debug(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Error(msg string, args ...interface{})
}

Logger defines the interface for logging

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL