C# Rest API Post - c#

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);

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,

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;

HTTP Client Patch method with Asp.net core 2.1, bad request

Using HttpClient to perform a PATCH method request is getting an bad request error
var patchDoc = new JsonPatchDocument<ClientOrganisationRequestArgs>();
patchDoc.Replace(e => e.Name, clientOrganisationRequestArgs.Name);
var serializedDoc = JsonConvert.SerializeObject(patchDoc);
var requestContent = new StringContent(serializedDoc, Encoding.UTF8, "application/json-patch+json");
var httpResponseMessage = await _httpClient.PatchAsync(
$"api/orgs/{clientOrganisationRequestArgs.ClientRefId}", requestContent);
Model
public class ClientOrganisationRequestArgs
{
public int ClientRefId { get; set; }
public string Name { get; set; }
public string DefaultTimezone => "AUSTRALIA/SYDNEY";
public string CustomStylePath { get; set; }
}
Getting 400 with bad request
Postman also show an 500 internal server error with body as raw
Authorization and accept header
_httpClient.DefaultRequestHeaders.Add(
HeaderNames.Accept, "application/vnd.yellowfin.api-v1.3+json");
_authorizationHeader =
$"{_authorizationHeader}, token={accessToken.SecurityToken}";
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(
HeaderNames.Authorization, _authorizationHeader);
You have application/json-patch+json as content type
//...
var requestContent = new StringContent(serializedDoc, Encoding.UTF8, "application/json-patch+json");
//...
But based on the docs shown it is expecting simple application/json content type header
var requestContent = new StringContent(serializedDoc, Encoding.UTF8, "application/json");
Also based on the example in the shown doc, the payload is a plain JSON document and does not really appear to be following the JSON Patch document format. This may result in the API not recognizing the request content.
I suggest serializing the payload to match the example given
string serializedDoc = JsonConvert.SerializeObject(clientOrganisationRequestArgs);
StringContent requestContent = new StringContent(serializedDoc, Encoding.UTF8, "application/json");
string url = $"api/orgs/{clientOrganisationRequestArgs.ClientRefId}";
var httpResponseMessage = await _httpClient.PatchAsync(url, requestContent);
assuming
public class ClientOrganisationRequestArgs {
[JsonProperty("clientRefId")]
public int ClientRefId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("defaultTimezone")]
public string DefaultTimezone => "AUSTRALIA/SYDNEY";
[JsonProperty("customStylePath")]
public string CustomStylePath { get; set; }
}

RestSharp doesn't get data or content of response

I have a route in my web service that receives POST request with Json body and returns simple array in Json format. I'm using PostMan for testing route and it works perfectly. but when I'm using RestSharp it doesn't get any content (or data in deserialization case).
Here is my C# code :
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
string bodyraw = JsonConvert.SerializeObject(user)
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("application/json", bodyraw, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteTaskAsync<Profile>(request);
return response.Data.Address;
}
And here is the Profile Class:
public class Profile
{
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Postal_code { get; set; }
public string Education { get; set; }
public string Gender { get; set; }
public string Age { get; set; }
public string Default_contact { get; set; }
public override string ToString()
{
return string.Concat(Name," " ,Family, " ", Address);
}
}
And this is PostMan OutPut:
{
"Name": "Holma",
"Family": "Kool",
"Email": "dr#gmail.com",
"Mobile": "09063094744",
"Address": "some city- basic av. sq 60",
"Postal_code": "10246666",
"Education": "1",
"Gender": "male",
"Age": "35"
}
And the PHP code that I used is:
function silverum_update_user_profile($request ){
$parameters = $request->get_json_params();// this is a WordPress method and works just fine
$name=sanitize_text_field($parameters['name']);
$family=sanitize_text_field($parameters['family']);
$email=sanitize_text_field($parameters['email']);
$mobile=sanitize_text_field($parameters['mobile']);
$address=sanitize_text_field($parameters['address']);
$postal_code=sanitize_text_field($parameters['postal_code']);
$education=sanitize_text_field($parameters['education']);
$gender=sanitize_text_field($parameters['gender']);
$age=sanitize_text_field($parameters['age']);
$extdp = [
"Name"=>$name,
"Family"=>$family,
"Email"=>$email,
"Mobile"=>$mobile,
"Address"=>$address,
"Postal_code"=>$postal_code,
"Education"=>$education,
"Gender"=>$gender,
"Age"=>$age
];
return $extdp;
}
When PHP method returns "Parameter" its OK and both PostMan and RestSharp can see output content but when method Returns new Array only PostMan is able to recive returnd object. I spent a couple of hour on the issue but didn't get anywhere. help please.
Try using the AddJsonBody() method within the RestRequest object as opposed to adding the parameter manually.
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.AddJsonBody(user);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteAsync<Profile>(request);
return response.Data.Address;
}

Creating Restsharp call to add parameters in an array

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);

Categories

Resources