RestSharp Post Request Array Object - c#

I've been looking for a way to use RestSharp C# to send POST request with the JSON below.
[{"Guid": "ccda117f-a9b5-4f54-ab4a-07a9cf403ef7"}]
It starts with the bracket and I don't see any reference similar to this.
Can you provide any link or sample code that I can use for reference?
Thanks!
var client2 = new RestClient("https://test.rest.com/api/v2/notifications/channels/" + channelId + "/subscriptions");
var request2 = new RestRequest(Method.POST);
request2.AddHeader("cache-control", "no-cache");
request2.AddHeader("authorization", "Bearer " + access_token);
request2.AddHeader("Content-Type", "application/json");
var myJson = "[{\"Guid\": \"ccda117f-a9b5-4f54-ab4a-07a9cf403ef7\"}]";
request2.AddParameter("application/json", myJson, ParameterType.RequestBody);
IRestResponse response2 = client2.Execute(request2);

Related

Sending a PUT request to the ZENDESK API to update an organisation via c#

I'm getting a 422 error when sending the http rerquest to the zendesk API to update an organisation. The JSON I am sending is valid so not sure where the issue is. I am using the C# http client.
The code:
string host = "https://MYZENDESK.zendesk.com";
var file = "/api/v2/organizations/" + connectDetails.ToString() + ".json";
var details = this.richTextBox1.Text.Replace(#"\",#"\\");
var json = "{\"organization\": {\"details\" :\"" + details + "\"}}";
Console.Write(json);
Console.Read();
var jobject = JsonConvert.DeserializeObject<JObject>(json);
using (var client = new HttpClient())
{
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.DefaultRequestHeaders.Add("authorization", "Basic xxxxxxxxx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//var response = client.GetAsync(host + file).Result;
var response = client.PutAsync(host + file, new StringContent(json, Encoding.UTF8, "application/json")).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
}
I was hopeing this would work. I can update via postman just fine with the same configuration but there must be some issue with my code.
Found a solution using RestSharp. Had tried this previously but have found that an older version of RestSharp is needed:
using RestSharp;
//use RestSharp v106.1
static void APIcall() {
var client = new RestClient("https://xxxxx.zendesk.com/api/v2/organizations/xxxxx");
client.Timeout = -1;
var request = new RestRequest(Method.PUT);
request.AddHeader("content", "application/json");
request.AddHeader("Authorization", "Basic xxxxx");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "_zendesk_cookie=xxxxxx");
var body = xxxxx
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadLine();
}
APIcall();

Returning result from RestClient.Content ('result' is a variable but is used like a type)

I'm new to c# and I'm trying to return the data I get from a restClient to use later in my Program.
public string SlackGet(string parameterJsonObject, string url, string token)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");
request.AddParameter("application/json", parameterJsonObject, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result =(response.Content);
Console.WriteLine(result);
return(result);
Console.WriteLine($"done!");
}
With this I am recieving the following error 'result' is a variable but is used like a type
What am I doing wrong?
TIA

Is there a way to convert this Twilio CURL to RestClient?

I would like to know how to convert this Twilio CURL code to RestClient
I am stuck in the request.AddParamenter() I have not idea how to format it order to pass the Twilio SID,Token, From, To and Body Text Message.
curl -X POST https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json \
-data-urlencode "Body=Hi there" \
-data-urlencode "From=+15017122661" \
-data-urlencode "To=+15558675310" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
To this:
var client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This is my code now that compile 100% and after I run the code I get a response "Complete" no error message and no entry at twilio dashboard either, it does not send the text message, any idea your help will be much appreciate.
RestClient client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/ACet53f18a4734c339488c1845e619dd9g/Messages.json");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("ACet53f18a4734c339488c1845e619dd9g:daskshdsjkahkashd90ud09as8dasjkhdsa9"));
request.AddHeader("Authorization", "Basic " + base64authorization);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Body", "Hello World");
request.AddParameter("From", "+15017122661"); //- My Twilio number goes
request.AddParameter("To", "+15017122661");
IRestResponse response = client.Execute(request);
string ResStatus = response.ResponseStatus.ToString(); //- Complete after successfully run.
You can send a RestClient request like this.
RestClient client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN"));
request.AddHeader("Authorization", $"Basic {base64authorization}");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Body", "Hi");
request.AddParameter("From", "+15017122661");
request.AddParameter("To", "+ 15558675310");
IRestResponse response = client.Execute(request);

RestSharp body always empty

I need to call a Post service with RestSharp
var client = new RestClient(url);
var request = new RestRequest(url,Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
);
var response = client.Post(request);
The problem is that the request's body is always null and the json body is added as a parameter
Any ideas?
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
seems to not accept json, even with the content-type set as "application/json"
My solution:
var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);
var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);
var response = client.Execute(request);

Converting HttpClient to RestSharp

I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.
client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;
This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
Am I missing something with authenticating?
This has fixed my problem:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization",
string.Format("Bearer " + access_token),
ParameterType.HttpHeader);
var response = client.Execute(request);
Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix
Try this
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:
private void InitializeClient()
{
_client = new RestClient(BASE_URL);
_client.DefaultParameters.Add(new Parameter("Authorization",
string.Format("Bearer " + TOKEN),
ParameterType.HttpHeader));
}

Categories