0

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

user3920526
  • 404
  • 4
  • 20
  • [Docs](https://www.deepl.com/docs-api/documents/translate-document/) state the file should be transferred under `file` parameter, so perhaps `content.Add(fileContent, "file");` ? – orhtej2 Apr 24 '23 at 14:50
  • Also from the same docs you should send `auth key` as header `Authorization: DeepL-Auth-Key [yourAuthKey]` not form part. – orhtej2 Apr 24 '23 at 14:52

2 Answers2

1

If possible, I'd recommend to use the official client library from DeepL for C#. It implements all the requests for you correctly and offers a simple interface.

One thing I noticed is that you're putting your auth_key into the body of the request, while it should be a header. For example (this will set it for all requests with this client)

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);

Missing this will likely lead to 400 bad request errors.

Gaze
  • 149
  • 1
  • 9
  • I was following this article https://support.deepl.com/hc/en-us/articles/360020705539-Sending-a-POST-request – user3920526 Apr 24 '23 at 16:23
  • This is not the right answer. Please look at the article above. – user3920526 Apr 24 '23 at 17:12
  • 1
    The API docs are a better source for this, they have cURL and HTTP request [examples](https://www.deepl.com/docs-api/documents/translate-document/) for exactly what you're trying to do. If you just compare your request object to the one listed in the docs, you can see what is different. Again though, it's much easier to use the client libraries. I linked the one for C#. – Gaze Apr 25 '23 at 07:51
0

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; }
}
user3920526
  • 404
  • 4
  • 20