RestSharp Post Json Object - c#

I am trying to Post a simple Json object using RestSharp to add a new product. I'm getting an error response from the server
"{"status":400,"error":"There was a problem in the JSON you submitted: unexpected character (after ) at line 1, column 2 [parse.c:724] in '{'product':{'name':'Product name','opt1':'Colour'}}"}"
My code:
////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";
IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
Resource = "https://api.targetsite.com/products/"
};
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);
IRestResponse response = restClient.Post(request);
////
I managed to achive the result I wanted using a curl statment but I would like to do it using RestSharp.
Curl statment -
curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'
This HttpClient call also works fine
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>");
request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}

It looks like a limitation on the API you are calling.
When you send the json with curl, you're using different delimiters (" instead of ').
My guess is that the API you're calling doesn't properly deserialize the JSON when ' is used.
What you can try is replacing the escaped ' with " or replace this line in your code : request.AddJsonBody(json)
with
request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) provided that you have installed the newtonsoft package.

Related

'invalid_grant' error on API call with RestSharp

I need to convert that curl request to c#. Im using RestSharp. curl request:
> curl -X POST -i https://gw.api.alphabank.eu/sandbox/auth/token \
-u "{{client_id}}:{{client_secret}}" \
-d "grant_type=client_credentials&scope=account-info-setup"
I tried the following code but I end up with 'invalid_grant' error as a response.
Any ideas what i'm doing wrong?
My code:
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.POST;
client.Authenticator = new HttpBasicAuthenticator(ABclientID, ABclientSecret);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("scope", "account-info-setup");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/x-www-form-urlencoded"; };
IRestResponse response = client.Execute(request);
this sample code is generated by Postman and it's working for my api which accepts application/x-www-form-urlencoded, can you add your parameters like this? Or create and make your request works on Postman and generate to C#-RestSharp it's usually works for me with minor changes.
var client = new RestClient("url");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("userId", "1234");
request.AddParameter("count", "5");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Turns out "invalid_grant" meant wrong credentials. I was giving wrong client-secret.
Request was succesfull after correcting the client_secret.

Posting to WS with Restsharp is not successfull

There is an external webservice that I need to post some data to create a device. They use swagger and in the swagger I can test and it works but when I use restsharp it does not work correctly. It does not give me any error (returns 200 as status code), but it does not create a device.
PS: a GET method of Wwebservice is working but the Post is not
here is the curl when I use swagger
curl -X POST "website/keys/generate" -H "accept: application/json" -H "Authorization: Bearer blablablablablabla"
-H "Content-Type: application/json" -d "{\"deviceIds\":[\"10000000\"],\"keyNames\":[\"DeviceKey1\"],
\"externalReference\":\"ERD-1\"}"
as json, the request should be
{
"deviceIds": [
"10000000"
],
"keyNames": [
"DeviceKey1"
],
"externalReference": "ERD-1"
}
and here is my code
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddParameter("deviceIds", deviceGenerationRequest.deviceIds.ToArray());
request.AddParameter("keyNames", deviceGenerationRequest.keyNames.ToArray());
request.AddParameter("externalReference", deviceGenerationRequest.externalReference);
var result = await _apiCaller.CallAPI(url, request);
and here is the CallAPI method's content
var client = new RestClient(url);
client.AddDefaultHeader("Authorization", "Bearer " + _token);
IRestResponse response;
response = await client.ExecuteGetAsync(request);
What is my mistake?
Edit:
instead of Restsharp, I've used HttpWebResponse and it works
var query = JsonConvert.SerializeObject(deviceGenerationRequest);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer blabla");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(query);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result3 = streamReader.ReadToEnd();
}
There are two ways to post data using rest sharp
Case 1
Pass all the parameters as a json in single paramter and use content type to application\json
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n \"deviceIds\": [\r\n \"10000000\"\r\n ],\r\n \"keyNames\": [\r\n \"DeviceKey1\"\r\n ],\r\n \"externalReference\": \"ERD-1\"\r\n}", ParameterType.RequestBody);
Case 2
Pass parameters individually. If you are individually sending parameters then change content type to this
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("deviceIds", deviceGenerationRequest.deviceIds.ToArray());
request.AddParameter("keyNames", deviceGenerationRequest.keyNames.ToArray());
request.AddParameter("externalReference", deviceGenerationRequest.externalReference);
I am not sure about the resolution but this is most likely be the case.Apart from this everything looks good

C# RestAPI Call

I am trying too make a rest call with C# for the first time.
I think im very close but i get an error message : Error: 400 - Bad Request.
Here is my Code:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.test123.com/oauth2/token"))
{
string webstring = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id=${2}&client_secret={3}", access_code_string, RedirectURI,ClientId, ClientSecret);
Console.WriteLine(webstring);
request.Content = new StringContent(webstring);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
Console.WriteLine("Access token: " + response);
}
}
Here is an sample code from Curl
curl -X POST \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "grant_type=authorization_code&code=dlZE0KFxhM&redirect_uri=http%3A%2F%2Fclient%2eexample%2Ecom&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET"
"https://api.test123.com/oauth2/token"
This is the description:
Obtain an access token
After you have received the authorization code you can request an access token.
Method
POST
URL
https://api.test123.com/oauth2/token
Request format
application/x-www-form-urlencoded
Request parameters
Name Type Description
grant_type String Value must be set to authorization_code
code String The authorization code
client_id String
client_secret String
redirect_uri String The URL where the response is sent. Must match the registered redirect URI.
Response format
application/json
I took an different approach
public void call()
{
string access_code_string = Read_Json_Values("accsess_code");
string webstring = String.Format("https://api.test123.com/oauth2/token?grant_type=authorization_code&code={0}&client_id=${1}&client_secret={2}&redirect_uri={3}", access_code_string, ClientId, ClientSecret, RedirectURI);
var client = new RestClient(webstring);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Bearer xxxx");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.Content);
}

How to convert curl "--user" command to Restsharp?

My curl is
curl -X POST -d "email=jeff#example.com" -d "password=*******"
--user admin#example.com:password https://example.com/admin/web/users/add
what I have so far is
var client = new RestClient("https://example/admin/web/users/add");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("application/x-www-form-urlencoded", "email=jeff#example.com" + "password=********", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
what i dont understand is where do I put
--user admin#example.com:password
Unless specified otherwise, curl uses HTTP Basic authentication when making HTTP(S) requests.
In RestSharp, HTTP Basic auth is provided via the RestSharp.Authenticators.HttpBasicAuthenticator type:
var client = new RestClient("https://example/admin/web/users/add");
client.Authenticator = new HttpBasicAuthenticator("admin#example.com", "password");
...

Using RestSharp with Gerrit REST API

I want to use RestSharp to issue Api calls to Gerrit but I'm having trouble with authentication.
For example there is the curl command which works:
curl --digest --user VladDracul:5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA http://localhost:8080/a/groups/
but how can I give the --user to a restSharp call?
myAuth = new HttpBasicAuthenticator("VladDracul","5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");
restClient = new RestClient(BaseUrl);
restClient.Authenticator = myAuth;
var request = new RestRequest(Method.GET);
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");
var response = restClient.Execute(request);
The response I get is "Unauthorized"
I found the answer. Adding the line gets it working.
var request = new RestRequest(Method.GET);
request.Credentials = new NetworkCredential("VladDracul", "5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");;
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");

Categories

Resources