Search code examples
c#asp.net-web-apideepl

How to make a HttpPost request to a DeepL Api


I am trying to post a html file in a DeepL Api. But somehow I am getting a bad request 400 all the time. Here is my code, file and the error message that I am receiving. Please help me figure it out. Thank you in advance My file reside in the temp file location here is the code. I have followed this article : https://support.deepl.com/hc/en-us/articles/360020705539-Sending-a-POST-request

    string uploadFilePath = htmlfile.FullName;    //this is the full path from FileInfo

FullName: C:\Users\username\AppData\Local\Temp\6af93935-6e76-4222-b12f-2e21d350b4da\wfujwrv5.5t3.html . It has the extension as .html

    string apiBaseAddress = "https://api.deepl.com/v2/document";
    string fileContentType = "application/x-www-form-urlencoded"; // "text/html";    
    using (var client = new HttpClient())
        {
            var values = new[]
            {
                new KeyValuePair<string,string>("auth_key",key),
                new KeyValuePair<string,string>("target_lang",target_lang), //it is set to DE for now 
            };
            using var content = new MultipartFormDataContent();
            foreach (var val in values)
            {
                content.Add(new StringContent(val.Value), val.Key);
            }
            var fileContent = new StreamContent(new FileStream(uploadFilePath, FileMode.Open));

            fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(fileContentType);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = uploadFilePath };
           
            content.Add(fileContent);

           
            //client.BaseAddress = new Uri(apiBaseAddress);
            var result = client.PostAsync(apiBaseAddress, content).Result; // it throws a Bad Request 400 error 

My Html file

    <!DOCTYPE html>
       <html>
         <head></head>
           <body>
               <strong>
                ItemName 101
               </strong> 
               -Description about the item
               <br />
               <br /> Testing 101 
            </body>
        </html>

Error that I get as of now

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n  transfer-encoding: chunked\r\n  access-control-allow-origin: *\r\n  x-trace-id: 7da3ba4922486baed9aa109dbb97ce50\r\n  strict-transport-security: max-age=63072000; includeSubDomains; preload\r\n  server-timing: l7_lb_tls;dur=106, l7_lb_idle;dur=0, l7_lb_receive;dur=79, l7_lb_total;dur=195\r\n  access-control-expose-headers: Server-Timing\r\n  Date: Mon, 24 Apr 2023 12:17:13 GMT\r\n  Content-Type: application/json; charset=utf-8\r\n  Content-Length: 32\r\n}}

enter image description here


Solution

  • I have added my code back. This is how you call a DeepL API . There is a free version as well where auth_key is not needed. And the URL is different. Please check the article I posted in the question. Cheers :)

    using (var client = new HttpClient())
            {
                var multiForm = new MultipartFormDataContent();
    
                //The StreamContent, StringContent, inherits from HttpContent,it uses data coming from an underlying Stream to build a request body.
                multiForm.Add(new StringContent(key, Encoding.UTF8, MediaTypeNames.Text.Plain), "auth_key");
                multiForm.Add(new StringContent(target_lang, Encoding.UTF8, MediaTypeNames.Text.Plain), "target_lang");
    
                //html file to upload 
                var fileContent = new StreamContent(File.OpenRead(htmlfile.FullName));
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Text.Html);
                multiForm.Add(fileContent, "text", htmlfile.Name);
    
                var url = "https://api.deepl.com/v2/translate";
                var response = await client.PostAsync(url, multiForm);
    
                var responseJson = await response.Content.ReadAsStringAsync();
                SingleResponse SingleResponseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<SingleResponse>(responseJson);
    
                //returns null if not found 
                return SingleResponseObj.translations.Select(x => x.text).FirstOrDefault();
            }
    

    Helper classes for Deserialized object

     public class SingleResponse
    {
        public Translation[] translations { get; set; }
    }
    
    /// <summary>
    /// Generated from JSON
    /// </summary>
    public class Translation
    {
        public string detected_source_language { get; set; }
        public string text { get; set; }
    }