Search code examples
c#deepl

I want to POST from C # to DeepL API


I want to POST from C # to DeepL API. It just doesn't work. Can anyone please tell me how?

var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api-free.deepl.com/v2/translate");

httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("auth_key", "auth_key");
httpWebRequest.Headers.Add("target_lang", "JA");

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    strSendJson = "{" +
                    "\"text\":\"" + strData.Trim() + "\"," +
                    "}";
}


Solution

  • The DeepL Simpulator is a great place to start out: https://www.deepl.com/docs-api/simulator

    When using POST, the auth_key is just another field in the form fields, its not a header.

    Because the content type is specified as x-www-form-urlencoded you are expected to send the data as a url encoded form, not JSON. Over the wire this should look something like:

    auth_key=[yourAuthKey]&text=Hello, world&target_lang=JA
    

    The following shows how to send this POST request from C# using HttpClient:

    string authKey = "~MyAuthKey~";
    
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");       
    Dictionary<string, string> data = new Dictionary<string, string>
    {
        { "auth_key", authKey },
        { "text", strData.Trim() },
        { "target_lang", "JA" }
    };
    var response = await client.PostAsync("https://api-free.deepl.com/v2/translate", 
        new System.Net.Http.FormUrlEncodedContent(data));
    response.EnsureSuccessStatusCode();
    
    var json = response.Content.ReadAsStringAsync().Result;
    deeplResponseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DeepResponse>(json);
    
    foreach(var tx in deeplResponseObj.translations) 
        Console.WriteLine("\"{0}\" (from {1})", tx.text, tx.detected_source_language);
    

    The following class definitions help with deserialization of the response:

    public class DeepResponse
    {
        List<DeepTranslation> translations { get;set; } = new List<DeepTranslation>();
    }
    
    public class DeepTranslation
    {
        public string detected_source_language { get;set; }
        public string text { get;set; }
    }