Question Convert a curl call from JavaScript to C #

sn_race

Member
Joined
Feb 27, 2022
Messages
11
Programming Experience
5-10
Hello,
could you help me convert the JavaScript code of the POST call found in the function:

JavaScript:
async function ryte ({useCaseId, inputContexts})


In a C # code, I can't find the right way, I don't know much JavaScript, I tried like this:

C#:
private void GetRytrContent (string _langID, string _toneID, string _usecaseID)
        {
            string api_key = "<MY-API-KEY>";

            WebRequest wr = WebRequest.Create ("https://api.rytr.me/v1/ryte");
            wr.ContentType = "application / json";
            wr.Method = "POST";
            wr.Headers.Add ("Authentication", "Bearer" + api_key);

            using (StreamWriter sw = new StreamWriter (wr.GetRequestStream ()))
            {
                string data = "{" +

                                "\" languageId \ ": \" "+ _langID +" \ "," +
                                "\" toneId \ ": \" "+ _toneID +" \ "," +
                                "\" useCaseId \ ": \" "+ _usecaseID +" \ "," +

                                "\" inputContexts \ ": \" {\ "<USE-CASE CONTEXT-INPUT KEY-LABEL> \": \ "<VALUE> \"}, "+

                                "\" variations \ ": \" 1 \ "," +

                                "\" userId \ ": \" <UNIQUE USER ID> \ "," +

                                "\" format \ ": \" html \ "," +
                                "\" creativityLevel \ ": \" default \ "," +

                                "}";

                sw.Write (date);
            }

            WebResponse httpResponse = (WebResponse) wr.GetResponse (); //System.Net.WebException: 'Remote server error: (400) Invalid request.'

            using (StreamReader streamReader = new StreamReader (httpResponse.GetResponseStream ()))
            {
                var result = streamReader.ReadToEnd ();

                TxtDisplay.Text = result.ToString ();
            }
        }

but it gives me this error on WebResponse:

//System.Net.WebException: 'Remote server error: (400) Invalid request.'

This is the request curl:

C#:
curl \
  -H "Authentication: Bearer <API KEY>" \
  -H "Content-Type: application / json" \
  -d '{"languageId": "<LANUGAGE ID>", "toneId": "<TONE ID>", "useCaseId": "<USE-CASE ID>", "inputContexts": {"<USE-CASE CONTEXT -INPUT KEY-LABEL> ":" <VALUE> "}," variations ": 1," userId ":" <UNIQUE USER ID> "," format ":" html "," creativityLevel ":" default "} ' \
  -X POST https://api.rytr.me/v1/ryte

 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,245
Location
Chesapeake, VA
Programming Experience
10+
Use System.Text.Json or Newtonsoft.Json or string interpolation to create your JSON payload.

Use HttpClient to post the payload to the URI.

The hardest part from my point of view is if you choose to use serialization, generating the input context section will be difficult because the keys are dynamic, and that you need to serialize an object (with curly braces) instead of a dictionary (with square brackets).
 
Last edited:

sn_race

Member
Joined
Feb 27, 2022
Messages
11
Programming Experience
5-10
Usa System.Text.Json o Newtonsoft.Json o l'interpolazione di stringhe per creare il tuo payload JSON.

Utilizzare HttpClient per inviare il payload all'URI.

La parte più difficile dal mio punto di vista è se si sceglie di utilizzare la serializzazione, generare la sezione del contesto di input sarà difficile perché le chiavi sono dinamiche e che è necessario serializzare un oggetto (tra parentesi graffe) invece di un dizionario (con quadrato parentesi).

I took a look and I will modify it that way as you advise me, in the meantime I had made some changes:
I created the json string with "JsonConvert.SerializeObject", and added the "inputContexts" field that I had omitted, even though I had pasted it here in the code.

Now it returns me this message:
{"success": false, "message": "Sorry, we were unable to process your request. Please try again."}

I am doubtful if I am wrong in creating the field:
inputContexts = "{'INTEREST_LABEL': 'I propose you an exceptional new business'}",

or else ..., in the documentation it is not explained how to format it and with what data, I went back a bit through the JavaScript example, but possible that I'm wrong, this is what it asks:

"inputContexts": {"<USE-CASE CONTEXT-INPUT KEY-LABEL>": "<VALUE>"}

But what is: <USE-CASE CONTEXT-INPUT KEY-LABEL> ???
I assume that: <VALUE> his is the phrase from which he extrapolates the keywords to then create the post, so I have entered this as text: "I propose you a new exceptional business!".

Also I don't know if the "INTEREST_LABEL" field is right.

Ho provato a cercare su Google esempi C # per queste API Rytr, ma non riesco a trovare nulla !!

C#:
public class RytrData
{
public string languageId { get; set; }
public string toneId { get; set; }
public string useCaseId { get; set; }
public string inputContexts { get; set; }
public string variations { get; set; }
public string userId { get; set; }
public string format { get; set; }
public string creativityLevel { get; set; }
}

private void GetRytrContent(string _apyKey, string _langID, string _toneID, string _usecaseID)
{
WebRequest wr = WebRequest.Create("https://api.rytr.me/v1/ryte");
wr.ContentType = "application/json";
wr.Method = "POST";
wr.Headers.Add("Authentication", "Bearer " + _apyKey);

RytrData RytrData = new RytrData
{
languageId = _langID,
toneId = _toneID,
useCaseId = _usecaseID,
inputContexts = "{'INTEREST_LABEL':'Ti propongo un nuovo business eccezionale!'}",
variations = "1",
userId = "USER1",
format = "text",
creativityLevel = "default"
};
var json = JsonConvert.SerializeObject(RytrData, Formatting.Indented);

using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
string data = json.ToString();

sw.Write(data);
}

WebResponse httpResponse = (WebResponse)wr.GetResponse();

using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();

TxtDisplay.Text = result.ToString(); //{"success":false,"message":"Sorry, we were unable to process your request. Please try again."}
}
}
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,245
Location
Chesapeake, VA
Programming Experience
10+
variations is suppose to be an integer, not a string, if you look closely at your original curl example.

As for valid key names for the input contexts, I recall spending about 5 minutes poking around the Ryter web site and not getting closer to figuring it out. Maybe I should have been looking more closely at the sample code from GitHub, but by that time I gave up because I was too tired from a long day.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,245
Location
Chesapeake, VA
Programming Experience
10+
Also, I assume that you are putting in your userId and that the code you posted was just an example so that you don't accidentally leak your real user ID.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,245
Location
Chesapeake, VA
Programming Experience
10+
Look at lines 67-96 of the JavaScript sample code you linked to in post #1. Apparently you pass in a GUID like string to another REST API, and then you'll get back a key name. You the use that key name for the actual REST API that you wanted to call.
 

Latest posts

Top Bottom