Access a REST API with C# - c#

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

Related

How to call Rest API with Content and Headers in c#?

I am trying to call Rest API with content and headers in c#. Actually I am trying to convert to c# from Python code which is:
import requests
url = 'http://url.../token'
payload = 'grant_type=password&username=username&password=password'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request('POST', url, headers = headers, data = payload, allow_redirects=False)
print(response.text)
So far I am trying with:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
var tmp = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content =
{
}
};
var result = client.PostAsync(Url, tmp.Content).Result;
}
I have no idea how to put from Python code Headers (Content-Type) and additional string (payload).
If you use RestSharp, you should be able to call your service with the following code snipped
var client = new RestClient("http://url.../token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=username&password=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
I based my answer on the anwser of this answer.
Here a sample I use in one of my apps:
_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl),
Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");
using System.Net.Http;
var content = new StringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
Or use FormUrlEncodedContent without set header
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);
If you write UWP application, use HttpStringContent or HttpFormUrlEncodedContent instead in Windows.Web.Http.dll.
using Windows.Web.Http;
var content = new HttpStringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);

Can not upload Transient Document to Adobe Sign in C#

I'm trying to upload a transient document file to Adobe Sign in C#, and it has driven me to my wits end trying to get it to work.
I've even contacted Adobe, and even they don't know how to do it.
My code is as follows:
if (!File.Exists(#"documents\1-Registration Form.pdf"))
{
return;
}
Models objGetData = new Models();
RestClient objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
RestRequest objRequest = new RestRequest("transientDocuments", Method.POST);
objRequest.AddFile("file", File.ReadAllBytes(#"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-My Token Here-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
try
{
var objResultObjects = AllData(jsonLinq).First(c => c.Type == JTokenType.Array && c.Path.Contains("libraryDocumentList")).Children<JObject>();
}
catch(Exception ex)
{
ex.LogExceptionToDatabase();
}
return;
Here's the response that I'm getting as the result of my most recent attempt:
"{\"code\":\"NOT_FOUND\",\"message\":\"Resource not found\"}"
I typically get Bad request saying the file isn't present or a not found error, but they're not always the same.
All help will be appreciated.
EDIT:
The following code will give a response with a list of library docs so I know it's not the URL.
var objGetData = new Models();
var objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
var objRequest = new RestRequest("libraryDocuments", Method.GET);
objRequest.AddHeader("Access-Token", "- My Key -");
objRequest.RequestFormat = DataFormat.Json;
objRequest.AddBody(objGetData);
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
SOLUTION:
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
This did it. Apparently "file" is bad but "File" is okay.
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
Not sure if the URI is correct, check missing '/' on the end of the RestClient (shouldn't be needed but still).
Lastly if you browse to the location in Angular 1 does it give you the same issue? I ask as this is a lot lighter to test and you can see using F12 developer tools exactly what is coming back from the open https channel.

Trustpilot OAuth Restful API: Unable to PostAsync

I am trying to use the Trustpilot API, to post invitations to review products.
I have successfully gone through the authentication step as you can see in the code below, however I am unable to successfully post data to the Trustpilot Invitations API. The PostAsnyc method appears to be stuck with an WaitingForActivation status. I wonder if there is anything you can suggest to help.
Here is my code for this (the API credentials here aren't genuine!):
using (HttpClient httpClient = new HttpClient())
{
string trustPilotAccessTokenUrl = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken";
httpClient.BaseAddress = new Uri(trustPilotAccessTokenUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = "MyApiKey:MyApiSecret";
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Base64Encode(authString));
var stringPayload = "grant_type=password&username=MyUserEmail&password=MyPassword";
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(trustPilotAccessTokenUrl, httpContent).Result;
var accessTokenResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var accessTokenResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);
// Create invitation object
var invitation = new ReviewInvitation
{
ReferenceID = "inv001",
RecipientName = "Jon Doe",
RecipientEmail = "Jon.Doe#comp.com",
Locale = "en-US"
};
var jsonInvitation = JsonConvert.SerializeObject(invitation);
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", accessTokenResponseObject.AccessToken);
var invitationsUri = new Uri("https://invitations-api.trustpilot.com/v1/private/business-units/{MyBusinessID}/invitations");
// This here as a status of WaitingForActivation!
var a = client.PostAsync(invitationsUri, new StringContent(jsonInvitation)).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
This is how I solved the issue:
// Serialize our concrete class into a JSON String
var jsonInvitation = JsonConvert.SerializeObject(invitationObject);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var stringContent = new StringContent(jsonInvitation);
// Get the access token
var token = GetAccessToken().AccessToken;
// Create a Uri
var postUri = new Uri("https://invitations-api.trustpilot.com/v1/private/business-units/{BusinessUnitID}/invitations");
// Set up the request
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, postUri);
request.Content = stringContent;
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content.Headers.Add("token", token);
// Set up the HttpClient
var httpClient = new HttpClient();
//httpClient.DefaultRequestHeaders.Accept.Clear();
//httpClient.BaseAddress = postUri;
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
var task = httpClient.SendAsync(request);
task.Wait();
This question here on SO was helpful:
How do you set the Content-Type header for an HttpClient request?

Sentiment140 in Restclient Not working

The below code is for api call using restclient...But it is not getting response any one have idea about this?
var client = new RestClient("http://www.sentiment140.com");
var request = new RestRequest(Method.POST);
request.Resource = "api/bulkClassifyJson";
request.AddParameter("appid", "abcd#gmail.com");
request.RequestFormat = DataFormat.Json;
request.AddBody(text);
var response = client.Execute(request);
var serializer = new JavaScriptSerializer();
List<Sentimental> items = serializer.Deserialize<List<Sentimental>>(response.Content);
return items;

How to post a Request to Web API as Xml using RestSharp?

How to post a Request to Web API as Xml?
I'm using the below test:
[TestMethod]
public void Should_post_successfully_with_valid_userDetailsList_usingRestSharp()
{
// arrange
string url = string.Format("{0}/User/BulkLoad", this._baseUrlForLuis);
var client = new RestClient(url);
var request = new RestRequest(Method.POST)
{
RequestFormat = DataFormat.Xml
};
request.AddBody("<user></user>");
request.AddHeader("Accept", "application/xml");
// act
IRestResponse response = client.Execute<HttpResponseMessage>(request);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
and my action looks like below; it accepts a string:
[HttpPost]
public HttpResponseMessage BulkLoad([FromBody] string userDetailsListXml)
{
}
But userDetailsListXml is always null so the value is not passed over.
How to fix it?
I tried with Ajax Post and the below code gets passed and works fine:
$.post("http://www.domain.com/User/BulkLoad", {"" : "<user></user>"});
But how to make it work with RestSharp?
var personString = "<Person><Name>Person Name</Name></Person>"; // Your XML string
var restClient = new RestClient("http://localhost:56453/api/people");
var restRequest = new RestRequest("Post", Method.POST);
restRequest.RequestFormat = DataFormat.Xml;
restRequest.AddParameter("application/xml", personString, ParameterType.RequestBody);
var response = restClient.Execute(restRequest);
Don't forget to add folloing code in WebApiConfig.cs
config.Formatters.XmlFormatter.UseXmlSerializer = true;

Categories

Resources