I'm using restsharp to make rest api client. This is my code:
var client = new RestClient("https://url.com");
client.Authenticator = new SimpleAuthenticator("client_id", "testapi", "client_secret", "password");
var request = new RestRequest("webapi/rest/auctions", Method.GET);
request.AddParameter("limit", "10");
request.AddParameter("order", "auction_id");
request.AddParameter("page", "1");
request.AddParameter("offset", "0");
IRestResponse response = client.Execute(request);
Console.WriteLine("request: " + response.Content);
Response is always: {"error":"unauthorized_client"}
And here is information from documentation of this rest api
Related
TerminalAPIRequest terminalAPIRequest = new TerminalAPIRequest();
TerminalAPIResponse terminalAPIResponse = new TerminalAPIResponse();
var client = new RestClient("https://connect.squareupsandbox.com/v2/terminals/checkouts");
//client.Timeout = -1;
var request = new RestRequest("https://connect.squareupsandbox.com/v2/terminals/checkouts", Method.Post);
request.AddHeader("Square-Version", "2023-01-19");
request.AddHeader("Authorization", "Bearer token");
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(terminalAPIRequest);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Related Webhook Responses are found at webhook.site
. Now How can I get that response to My WPF application?
I try to access to the REST API from NetExplorer. It works when I send a request with postman :
But It doesn't with my C# code :
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
JsonResult result = new JsonResult(ReqAuth);
var request = new RestRequest(result.ToString(), Method.Post);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Here's the error message :
{"error":"Il n'existe aucune m\u00e9thode de l'API pouvant r\u00e9pondre \u00e0 votre appel."}
In english, there's no API method to resolve your call
If somebody can help me ...
Thanks
You are using the constructor of RestRequest wrong, the constructor does not take in the content (body) like that. Try using it with AddJsonBody like so:
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
var request = new RestRequest();
request.Method = RestSharp.Method.Post;
request.AddJsonBody(ReqAuth);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Documentation: https://restsharp.dev/usage.html#request-body
I have been trying to connect to DHL interface but i cannot get the token access key from C# code. here is my current code. Please let me know if you have a solution -
RestClient client = new RestClient();
client.ClearHandlers();
client.Timeout = -1;
client.BaseUrl = new Uri("https://api-sandbox.dhlecs.com/auth/v4/accesstoken");
client.Authenticator = new HttpBasicAuthenticator(ConfigurationManager.AppSettings["DHLClientId"], ConfigurationManager.AppSettings["DHLClientSecret"]);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("grant_type", "client_credentials");
IRestResponse response = client.Execute(request);
var local = response.Content.ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content.ToString();
}
else
{
throw new Exception($#"Unable to authorize with GLS. Contact IT");
}
here is the error i get -
https://api-sandbox.dhlecs.com/docs/errors/401.0000007"
>> Solution :
this needs to be removed -
request.Parameters.Clear();
I am trying to do this curl call to the new yahoo weather api with OAuth 1 like so:
[HttpGet]
public HttpResponseMessage getWeather()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://weather-ydn-yql.media.yahoo.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", "OAuth oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547473450\", oauth_nonce = \"Ll7ArdU1yN0\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", "oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547472939\", oauth_nonce = \"vu3HE92s6A3\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
HttpResponseMessage response = httpClient.GetAsync("forecastrss?location=hamilton&format=json").Result;
return response;
}
}
But when I run this it returns this error:
Please provide valid credentials. OAuth
oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR",
realm="yahooapis.com"
So it appears that my OAuth parameters are missing. My Question is how do I do a curl in ASP.NET C# with OAuth 1 authentication?
Figured it out using RestClient
var client = new RestClient("http://weather-ydn-yql.media.yahoo.com/forecastrss?location=hamilton&format=xml");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "ac0c256b-e727-4b01-b4fe-edd8b7d7073a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", "OAuth oauth_consumer_key="(MY CONSUMER KEY)",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1547481203",oauth_nonce="304ixaov43G",oauth_version="1.0",oauth_signature="(MY GENERATED SIGNATURE FROM POSTMAN)"");
IRestResponse response = client.Execute(request);
I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));