Creating Restsharp call to add parameters in an array - c#

I need to send the following parameters to an AP using Restsharp in my C# console app
I have looked on here and on other sites, but not found anything that I can get to work.
This is what the raw code looks like
{
"LicenceNumber":"511237P",
"CardNumber":"DB07067",
"ExternalID":"ID56758",
"Comments":"data uploaded via automated weekly process",
"Rules":"EU",
"Activities": [
{
"StartTime":"2019-04-14 09:00:00",
"Duration":"480",
"ActivityType":"Rest"
}
]
}
What I need to do is use the Restsharp request.AddAddParameter to add the StartTime, Duration and ActivityType to the Activities but I am not sure how to proceed.
What I have so far is the following:
static void PostRecord(string url)
{
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + Token);
request.AddParameter("LicenceNumber", LicenceNumber);
request.AddParameter("CardNumber", CardNumber);
request.AddParameter("ExternalID", ExternalID);
request.AddParameter("Comments", Comments);
request.AddParameter("Rules", Rules);
request.AddParameter("Activities", "Activities");
}
Any help would be much appreciated
****** UPDATE **********
I have amended my code after some more investigation it runs but says that the Activities details must be supplied so its not recognising the values in the array
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
var Activities= new Dictionary<string, object>();
Activities.Add("StartTime", "2019-04-14 09:00:00");
Activities.Add("Duration", "480");
Activities.Add("ActivityType", "Rest");
JsonObject o = new JsonObject();
foreach (var kvp in Activities)
{
o.Add(kvp);
}
JsonArray array = new JsonArray();
array.Add(o);
request.AddHeader("Authorization", "Bearer " + Token);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("LicenceNumber", LicenceNumber);
request.AddParameter("CardNumber", CardNumber);
request.AddParameter("ExternalID", ExternalID);
request.AddParameter("Comments", Comments);
request.AddParameter("Rules", Rules);
request.AddParameter("Activities", array.ToString());
IRestResponse response = client.Execute(request);

Create a object and then assign your values to it accordingly:
public class Activity
{
public string StartTime { get; set; }
public string Duration { get; set; }
public string ActivityType { get; set; }
}
public class RootObject
{
public string LicenceNumber { get; set; }
public string CardNumber { get; set; }
public List<Activity> Activities { get; set; }
}
You can use Auto Properties you can generate them from a website such as this
Then you can create an instance of that class and assign all the values you need like so:
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + Token);
// This how you assign your values for the RootObject class
RootObject MyObject = RootObject();
MyObject.LicenceNumber = LicenceNumber;
MyObject.CardNumber = CardNumber;
// then for the activities class you can do the following
MyObject.Activities = new List<Activity>();
MyObject.Activities.Add(new Activity(){StartTime = "2019-04-14 09:00:00", Duration = "480",ActivityType = "Rest"});
string jsonString = JsonConvert.SerializeObject(MyObject);
request.AddParameter("application/json", jsonString, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Related

How to resolve 400 error code, "one or more validation error occurred"

I am trying to fix a payment Api using visual studio c#, but I am getting 400 error message, it says that one or more validation error occurred.
please what could be my mistake?
I tried running the code in postman, and it worked fine.
Below is my code sample:
public class Root
{
public string amount { get; set; }
public string email { get; set; }
public string currency { get; set; }
public string initiate_type { get; set; }
public string transaction_ref { get; set; }
public string callback_url { get; set; }
}
var client = new RestClient("https://sandbox-api-d.squadco.com/transaction/initiate");
var rootObj = new Root
{
amount = "1000",
email = EmailV,
currency = "NGN",
initiate_type = "inline",
transaction_ref = "213445RT",
callback_url = "https://samplesite.com"
};
//serialization using Newtonsoft JSON
string JsonBody = JsonConvert.SerializeObject(rootObj);
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Authorization", "sandbox_sk_3fae7c45922315aa8cb2a16db028f50a596d5fbdf351");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", JsonBody, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Based on their doc, the amount is decimal
https://squadinc.gitbook.io/squad/payments/initiate-payment#sample-request
so you can try changing to decimal
var rootObj = new Root
{
amount = 1000,

C# Rest API Post

I am trying to get a REST API to feed into https://www.scheduleit.com/faq/10640/is-there-a-rest-api-or-webhooks
I have the get working, put the post I always get
"{"status": "error", "status_code": "404", "message": "Not Found - Invalid End Point for Method POST"}"
Code is
var client = new RestClient("https://www.scheduleit.com/api/");
var request = new RestRequest(this.TokenEndPoint, Method.POST);
//client.Authenticator = new HttpBasicAuthenticator(userName, password);
request.AddHeader("Authorization", "Basic xxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("Cache-Control", "no-cache");
request.AddParameter("title", "Title Test");
request.AddParameter("owner", "813");
request.AddParameter("date_start", "2022-12-05");
request.AddParameter("date_end", "2022-12-06");
IRestResponse response = client.Execute(request);
Any suggestions
Have tried various ways of coding
The endpoint you specified doesn't exist. You need to include the resource target;
/api/groups
/api/resources
/api/events
/api/labels
/api/reports
You also need to pass arguments in a JSON Body, not as query parameters.
This is how it should look;
public class RequestBody {
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("owner")]
public string Owner { get; set; }
[JsonPropertyName("date_start")]
public DateTime DateStart { get; set; }
[JsonPropertyName("date_end")]
public DateTime DateEnd { get; set; }
}
var body = new RequestBody {
Title = "Title Test",
Owner = "813",
DateStart = Date.Now(),
DateEnd = Date.Now()
};
var client = new RestClient("https://www.scheduleit.com/api/events");
var request = new RestRequest().AddJsonBody(body);
var response = await client.PostAsync(request, CancellationToken.None);

RestSharp.RestResponse instead of json string as Authentication Response

I have been working on using a Rest Api for authentication (https://api.vorexlogin.com/)
So far I have added the RestSharp library to dismiss errors to RestClient and RestRequest.
So far when I run the code that I have in the textbox I get this:
RestSharp.Response
The Response that is needed should be something like:
"success": true,
"result": {
"accessToken": "eyJhbGtccccc.xxxx.yyyyzzzzz",
"refreshToken": "67ZYfdsJFDKLS879337937DKJSDLGFSDFRDEMO=",
"accessTokenExpireOn": "2021-07-03T22:19:23.8330686Z",
"refreshTokenExpireOn": "2021-08-02T21:49:23.8330686Z"
}
Even if it failed it should still be a json file of some sort. I will provide my code below.
private async void button1_Click(object sender, EventArgs e)
{
var client = new RestClient("https://api.vorexlogin.com/v2/security/authenticate");
var request = new RestRequest("resources", Method.Post);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("application/x-www-form-urlencoded",
"grantType=password&userName=+"+ usernametbx + "&password=" + passwordtbx + "&tenant=" + tenanttbx, ParameterType.RequestBody);
var response = await client.PostAsync<IRestResponse>(request);
textBox1.Text = response.ToString();
}
public class IRestRepsonseList
{
public string accessToken { get; set; }
public string refreshToken { get; set; }
public string accessTokenExpireOn { get; set; }
public string refreshTokenExpireOn { get; set; }
}
public class IRestResponse
{
public bool success { get; set; }
public List<IRestRepsonseList> result { get; set; }
}
By using PostAsync<T> you tell RestSharp to deserialize the response to T. Your IRestResponse class doesn't implement ToString(), so the default object.ToString is used by your code, which just returns the instance class name.
I cloud also suggest you read the documentation, as you wrote lots of unnecessary code.
Here is an example of what you should be doing:
var client = new RestClient("https://api.vorexlogin.com/v2/security/authenticate");
var request = new RestRequest("resources", Method.Post)
.AddParameter("grantType", "password")
.AddParameter("userName", usernametbx)
.AddParameter("password", passwordtbx)
.AddParameter("tenant", tenanttbx);
var response = await client.PostAsync(request);
textBox1.Text = response.Content;

Read / Load JSON response from PHP Web API to WPF ComboBox

Below is my JSON response from PHP Web API. I need this "tradeType" to be loaded in WPF ComboBox after checking "success"is true/false, If false display Error message shown in "message"
{
"success":"true",
"message":"Trade Type List",
"tradeType":[
{"id":1, "name":"Coaching Class"},
{"id":2,"name":"Food Supply"},
{"id":3,"name":"Marriage Bureau"}
]
}
I am new to WPF and Web API, what i have tried is
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var jsonString = response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<List<TradeType>>(jsonString);
cmbTrade.ItemsSource = users;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
var jsonString = response.Content.ReadAsStringAsync();
You are missing an await here so the call is fired but not awaited. Also have Task in var instead the string.
var jsonString = await response.Content.ReadAsStringAsync();
or use the non-async version.
public class TradeType
{
public int id { get; set; }
public string name { get; set; }
}
public class Root
{
public string success { get; set; }
public string message { get; set; }
public List<TradeType> tradeType { get; set; }
}
private void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
myDeserializedClass.tradeType.Insert(0, new TradeType { id = 0, name = "-Select-" });
cmbTrade.ItemsSource = myDeserializedClass.tradeType;
cmbTrade.DisplayMemberPath = "name";
cmbTrade.SelectedValuePath = "id";
cmbTrade.SelectedIndex = 0;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}

Get the ok massage from http posrequest

{
"token_type": "bearer",
"access_token": "ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidG9rZW5EYXRhIjogInpjeXNxSWcvbnBJTjBZWG5BSlpLa0JJQTRERnVMK2JCcTFrT0VhbWxCbXRieHJITFdhbVZBVnluSzl2U0dQRVpZdW1TZ1dQRERwemU3UEphSWhPTjJIeGgvWURHL09qalFyQXZFSHlRRkRucUFUM05NK3ZhY2RKMnBaTlFrYVpHNEU4MjhkVFZpMnduTml2N1g3OHR4VmkxcS84bnBmN25NcWc1UkZlZ1VockhPUUU1WXJuMlVsRmJTV200dDNsTHoyWTJpa2ZMOURJOTVBTHIvV25rdjdhWkljNlJ1Rld5OThid05ZOHpCMXc9IiwNCiAgImNsaWVudElEIjogImNhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOCIsDQogICJyZXBseVVybCI6ICJodHRwOi8vbG9jYWxob3N0IiwNCiAgIm5iZiI6IDE1MTMwNTkxMTcsDQogICJleHAiOiAxNTEzMDYwOTE3LA0KICAiaWF0IjogMTUxMzA1OTExNw0KfQ.ixRDlLYfrJ-OQs6LzkLhf07skR9z1i-3w1u7rtRppgE",
"expires_in": 1800.0,
"refresh_token": "zcysqIg/npIN0YXnAJZKkBIA4DFuL+bBq1kOEamlBmtbxrHLWamVAVynK9vSGPEZgS5OAD7gpY2OoBSeaHH48aQ/ER3WZOnOijWQrxEFNKU="
}
This is what i have json response. i want to display acces_token from this.so i want code line.
this is the code I try to get this json.
public async Task NewMethodAsync()
{
try
{
HttpClient objClient = new HttpClient();
Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
Dictionary<string, string> pairs = new Dictionary<string, string>();
var client_ID = "ca647d7796c548209cdda9ed004c38aa5248171708028004628";
var client_secret = "QXBwcm92YWxCb3RfVE9H7auiwc6RhE6ldS6WGsqWh2NhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOA==";
pairs.Add("grant_type", "client_credentials");
pairs.Add("reply_url", "http://localhost");
FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
// httpContent.Headers.Add("Authorization", "Basic " + encordedString);
//httpContent.Headers.Add("Authorization", "Basic " + encordedString);
// httpContent.Headers.Add["Authorization"] = "Basic" + encordedString;
objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);
HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
if (respon.IsSuccessStatusCode)
{
Console.WriteLine(respon.Content.ReadAsStringAsync().Result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You need to install Newtonsoft.Json library and use this code:
dynamic json = JsonConvert.DeserializeObject(result);
string token = json.refresh_token;
Just create response class
public class Response
{
public string token_type { get; set; }
public string access_token { get; set; }
public double expires_in { get; set; }
public string refresh_token { get; set; }
}
Then use Newstonsoft Json - https://www.nuget.org/packages/newtonsoft.json/
var response = JsonConvert.DeserializeObject<Response>(result);
Console.WriteLine(response.access_token);

Categories

Resources