gmonarque / go-json-translate

Translate json files / i18n locales
Apache License 2.0
18 stars 2 forks source link

Deepl API request not formed properly #3

Closed pdrhlik closed 2 weeks ago

pdrhlik commented 1 year ago

Hi,

The program is not working. It's probably because it targets an older Deepl API version? I'm not sure. The first issue is with authentication.

All requests return 403 Forbidden because they don't send a proper Authorization header.

Sample curl request from official Deepl API looks like this (request body can be either application/x-www-form-urlencoded or application/json):

curl -X POST 'https://api-free.deepl.com/v2/translate' \
--header 'Authorization: DeepL-Auth-Key [yourAuthKey]' \
--header 'Content-Type: application/json' \
--data '{
  "text": [
    "Hello, world!"
  ],
  "target_lang": "DE"
}'

Rewriting the POST request to something like this seems to work:

data := url.Values{}
data.Set("source_lang", config.Source_lang)
data.Set("text", source_text)
data.Set("target_lang", config.Target_lang)

url := config.Api_endpoint
contentType := "application/x-www-form-urlencoded"

client := &http.Client{}
req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
    fmt.Println(err)
    return translation, errors.New(`req error`)
}
req.Header.Add("Content-Type", contentType)
req.Header.Add("Authorization", "DeepL-Auth-Key "+config.Api_key)

resp, err := client.Do(req)
if err != nil {
    return translation, errors.New(`client do error`)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)

Then it seems to be working :-) Let me know if you need more info or some help with that.

Cheers, Patrik

gmonarque commented 1 year ago

Hello, thanks, I'll look into it; the call was working up to april (at least)