This may be too specific of an issue for assistance on, but I'm at a roadblock and don't know where else to turn.
I am POSTing to a website via REST API and their documentation states:
var client = new RestClient("https://server_name/api/import/tickets");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Bearer {{access_token}}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
var yourArrayOfTickets = new List<Ticket>();
// TODO: populate the list
request.RequestFormat = DataFormat.Json;
request.AddBody(yourArrayOfTickets);
IRestResponse response = client.Execute(request);
I am sending
public static void MakeTicket(string token, string url,
string clientName, string clientLocation,
string ticketSource, string ticketType,
string title, string priority, string status,
string details, DateTime openDate, string queue)
{
TicketBody ticketBody = new TicketBody();
ticketBody.ClientName = clientName;
ticketBody.ClientLocation = clientLocation;
ticketBody.TicketSource = ticketSource;
ticketBody.TicketType = ticketType;
ticketBody.Title = title;
ticketBody.Priority = priority;
ticketBody.Status = status;
ticketBody.Details = details;
ticketBody.OpenDate = Convert.ToString(openDate.ToString("MM/dd/yyyy HH:mm:ss"));
ticketBody.Queue = queue;
var body = JsonConvert.SerializeObject(ticketBody);
var bodyList = new List<string>();
bodyList.Add(body);
var client = new RestClient(url + "/import/tickets");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddBody(bodyList);
IRestResponse response = client.Execute(request);
}
My bodyList JSON looks like
My response looks like
Their documentation states the required fields are:
The error message is too vague to help me, it just says I'm missing something but doesn't say what, and as far as I can tell, I'm passing in everything it needs.
As per the documentation screenshot, you have not included the required parameter AssgineeUsername. If you are specifying Queue, try passing it as empty, but include it in request.
ticketBody.Queue = queue;
ticketBody.AssgineeUsername = "";
So turns out I was building out the JSON object incorrectly for this. Instead of serializing the entire object, it needs to be a list.
Ticket ticketBody = new Ticket
{
ClientName = clientName,
ClientLocation = clientLocation,
TicketSource = ticketSource,
TicketType = ticketType,
Title = title,
Priority = priority,
Status = status,
Details = details,
OpenDate = Convert.ToString(openDate.ToString("MM/dd/yyyy HH:mm:ss")),
Queue = queue
};
List<Ticket> bodyList = new List<Ticket>();
bodyList.Add(ticketBody);
Related
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've got this piece of code that I am looping 100 times. As you can see below the number of loops is declared in the response I get from GET method. So it changes over time depending which number is inside the GET response body.
Inside the body I also have "threads": 3 So i would like to bind the number for how many threads are needed for the POST method (below)
Is it possible to do it? I've never done it before & I don't know where to begin.
for (var i = 0; i < test.loop; i++) //looping 100 times
{
Console.WriteLine("Loop count: " + i.ToString());
var newClient = new RestClient(url);
var newRequest = new RestRequest(Method.POST);
newRequest.AddHeader("Accept", "application/json");
newRequest.AddHeader("Authorization", $"{testCases.header[0].auth}");
newRequest.AddHeader("content-type", "application/json");
newRequest.AddJsonBody(bodyRequest);
var queryResult = newClient.Execute<object>(request);
var content = JsonConvert.SerializeObject(queryResult.Data);
Assert.IsTrue(content.Contains(testing.result.httpCode));
Assert.IsTrue(content.Contains(testing.result.reponseAssert.ToString()));
}
Example code for you ;
public async Task<GetResponse> GetDetails(GetRequest getRequest)
{
GetResponse apiResponseClass = new GetResponse();
var url = "your url";
var client = new RestClient(url);
var request = new RestRequest(url, Method.Post);
request.AddHeader("Password", "xxxx");
request.AddHeader("UserName", "yyyy");
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(getRequest);
request.AddParameter("application/json", body, ParameterType.RequestBody);
RestResponse response = await client.ExecuteAsync(request);
var output = response.Content;
return apiResponseClass;
}
I've been troubleshooting this for days now but still no luck.
I'm trying to send parameters to an API link provided by Microsoft O365 Power Automate, this API requires a customer number, company code, and posting date and in return, it will send me a table with the list of items that have the same customer number, company code, and posting date. When I'm doing testing in Postman the sends status code 200, but when using VS and my code it always returns a status code 400.
SoaController.cs
[HttpPost]
public async Task<IActionResult> Index(string company, string customer, string asof)
{
using (var client = new HttpClient())
{
SoaParams soaParams = new SoaParams
{
Posting_Date = asof,
Company_Code = company,
Customer_Number = customer
};
var SoaJson = JsonConvert.SerializeObject(soaParams);
var buffer = Encoding.UTF8.GetBytes(SoaJson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.BaseAddress = new Uri(SD.ApiUri);
var response = await client.PostAsync(SD.ApiUri, byteContent);
if (response.IsSuccessStatusCode)
{
return RedirectToAction(nameof(Success), Json(response));
}
else
{
return RedirectToAction(nameof(Failed), Json(response));
}
}
}
The below image shows that the parameters needed are correct.
But it's SuccessStatusCode always returns false
I use a code provided by PostMan that look like this:
public List<BapiOpenItemDto> GetResponse(SoaParams soaParams, string uri)
{
var SoaJson = JsonConvert.SerializeObject(soaParams);
var client = new RestClient(uri);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "[\r\n" + SoaJson + "\r\n]\r\n", ParameterType.RequestBody);
IRestResponse<List<BapiOpenItemDto>> response = client.Execute<List<BapiOpenItemDto>>(request);
return response.Data;
}
and its working now.
I am calling API with RESTSharp
var client = new RestClient("http://demoservice.com");
var request = new RestRequest("callapi", "put");
request.RequestFormat = DataFormat.Json;
string jsonaction = "{\"tokenid\":\"x123x45\",\"userid\":\"2456\",\"ip\":\"192.168.1.20\",\"transaction\":\"6\",\"actionCode\":\"78\",\"jtoken\":\"systemtoken\"}";
request.AddBody(new { action = "SAVE", data = "savedata", token = "systemtoken", jsonaction = jsonaction });
I am checking in debug data passing in request. and my expected output as follows
{"action":"SAVE","data":"savedata","token":"systemtoken","jsonaction":{"tokenid":"x123x45","userid":"2456","ip":"192.168.1.20","transaction":"6","actionCode":"78","jtoken":"systemtoken"}}
But getting
{"action":"SAVE","data":"savedata","token":"systemtoken","jsonaction":"{"tokenid":"x123x45","userid":"2456","ip":"192.168.1.20","transaction":"6","actionCode":"78","jtoken":"systemtoken"}"}
If anybody can guide how to post for JSON I have tried with Addbody and AddJsonBody but nothing works.
You can do this using the request.AddParameter() method:
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", data , ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content; // raw content as string
Where data is of the format:
data :
{
"action":"dosomething" ,
"data":"somedata" ,
"token":"sometoken",
"jsonAction": {
"tokenId": "",
...
}
Hope it helps!
I would suggest you to use JObject to create your body for a request like,
JObject jObject = new JObject();
jObject["action"] = "SAVE";
jObject["data"] = "savedata";
jObject["token"] = "systemtoken";
jObject["jsonaction"] = JObject.Parse("{\"tokenid\":\"x123x45\",\"userid\":\"2456\",\"ip\":\"192.168.1.20\",\"transaction\":\"6\",\"actionCode\":\"78\",\"jtoken\":\"systemtoken\"}");
And then pass this jObject to either
request.AddBody(jObject.ToString());
OR
request.AddJsonBody(jObject.ToString());
And for JObject you need to import using Newtonsoft.Json.Linq; namespace to your program and you can find this namespace in newtonsoft.json package.
You can even use like this
request.AddBody(new { action = "SAVE", data = "savedata", token = "systemtoken", jsonaction = JObject.Parse(jsonaction) });
But creating a JObject for your full json data is best that minimizes the error and exception while creating own json data with string
Output:
From two genius people I could complete following code
jsonaction objjsonaction = new jsonaction();
objjsonaction.tokenid = "x123x45";
objjsonaction.userid = "2456";
objjsonaction.ip = "192.168.1.20";
objjsonaction.transaction = "6";
objjsonaction.actionCode = "78";
objjsonaction.jtoken = gentoken("key"); // gentoken() is external function for generating token from key
string sobjjsonaction = Newtonsoft.Json.JsonConvert.SerializeObject(objjsonaction);
sobjjsonaction = sobjjsonaction.Replace("__", "-");
JObject jObject = new JObject();
jObject["action"] = "SAVE";
jObject["data"] = getpostdata(); // a function to generate data from db
jObject["token"] = gentoken("key"); // gentoken() is external function for generating token from key
jObject["jsonaction"] = JObject.Parse(sobjjsonaction);
string sObject = Regex.Replace(jObject.ToString(), #"\s+", "");
//request.Method = Method.PUT;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", sObject, ParameterType.RequestBody);
I am using postman and making an api post request where I am adding body with x-www-form-urlencoded key/values and it works fine in postman.
The issue arrises when I try it from c# using RestSharp package.
I have tried the following code below but not getting the response. I get "BadRequest" invalid_client error.
public class ClientConfig {
public string client_id { get; set; } = "value here";
public string grant_type { get; set; } = "value here";
public string client_secret { get; set; } = "value here";
public string scope { get; set; } = "value here";
public string response_type { get; set; } = "value here";
}
public void GetResponse() {
var client = new RestClient("api-url-here");
var req = new RestRequest("endpoint-here",Method.POST);
var config = new ClientConfig();//values to pass in request
req.AddHeader("Content-Type","application/x-www-form-urlencoded");
req.AddParameter("application/x-www-form-urlencoded",config,ParameterType.RequestBody);
var res = client.Execute(req);
return;
}
//Also tried this
req.AddParameter("client_id",config.client_id,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("grant_type",config.grant_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("client_secret",config.client_secret,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("scope",config.scope,ParameterType.RequestBody);
req.AddParameter("response_type",config.response_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);
//tried this too
var client = new RestClient("url-here");
var req = new RestRequest("endpointhere",Method.POST);
var config = new ClientConfig();
req.AddBody(config);
var res = client.Execute(req);
this working for me, it was generator from postman
var token = new TokenValidation()
{
app_id = CloudConfigurationManager.GetSetting("appId"),
secret = CloudConfigurationManager.GetSetting("secret"),
grant_type = CloudConfigurationManager.GetSetting("grant_type"),
Username = CloudConfigurationManager.GetSetting("Username"),
Password = CloudConfigurationManager.GetSetting("Password"),
};
var client = new RestClient($"{xxx}{tokenEndPoint}");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"app_id={token.app_id}&secret={token.secret}&grant_type={token.grant_type}&Username={token.Username}&Password={token.Password}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Access Token cannot obtain, process terminate");
return null;
}
var tokenResponse = JsonConvert.DeserializeObject<TokenValidationResponse>(response.Content);
I personally find this way to work better for me when sending Form-UrlEncoded data.
public void GetResponse() {
var client = new RestClient("api-url-here");
var req = new RestRequest("endpoint-here",Method.POST);
var config = new ClientConfig();//values to pass in request
// Content type is not required when adding parameters this way
// This will also automatically UrlEncode the values
req.AddParameter("client_id",config.client_id, ParameterType.GetOrPost);
req.AddParameter("grant_type",config.grant_type, ParameterType.GetOrPost);
req.AddParameter("client_secret",config.client_secret, ParameterType.GetOrPost);
req.AddParameter("scope",config.scope, ParameterType.GetOrPost);
req.AddParameter("response_type",config.response_type, ParameterType.GetOrPost);
var res = client.Execute(req);
return;
}
Details on this parameter type can be found here:
https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest#getorpost
Personally, I found AddObject() method quite useful, and cleaner when you have so many parameters to add.
public void GetResponse() {
var client = new RestClient("api-url-here");
var req = new RestRequest("endpoint-here",Method.POST);
var config = new ClientConfig();//values to pass in request
req.AddHeader("Content-Type","application/x-www-form-urlencoded");
req.AddObject(config);
var res = client.Execute(req);
return res;
}
If it worked on postman, you can just press the code button on the right hand side. This will provide a working example in multiple languages. It is the button above the information icon. I would post a screenshot of it, but I don't have 10 reputation to do so.
i have found this good for my scenario , it is working perfect,
var client = new RestClient("https://test.salesforce.com/services/oauth2/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&client_id=3MVG9U_dUptXGpYKew7P.oPwrIsvowP_K4CsnkxHJIEOUJzW0XBUUY3o12bLDasjeIPGVobvBZo8TNFcCY6J3&client_secret=3189542819149073716&username=integraciones%40lamarina.com.mx.dev&password=2Password!4iwZvMQKVAwkYyJRy50JlAHk", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine("Response.StatusCode: " + response.StatusCode);
Console.WriteLine("Response.Content: " + response.Content);
Console.WriteLine("Response.ErrorMessage: " + response.ErrorMessage);
https://dotnetfiddle.net/J64FR5
in my case this is what worked
req.AddParameter("client_id", "unigen-corporation", ParameterType.HttpHeader);
req.AddParameter("grant_type", "client_credentials", ParameterType.GetOrPost);
If you've copied the code from the postman, try removing the following:
request.AlwaysMultipartFormData = true;
In my case after removing this line code worked.
var client1 = new RestClient(URI);
var request1 = new RestRequest(Method.POST);
request1.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request1.AddParameter("client_id", "XX");
request1.AddParameter("client_secret", "XX");
request1.AddParameter("grant_type", "XX");
request1.AddParameter("role", "XX");
IRestResponse response1 = client1.Execute(request1);
System.Console.WriteLine(response1.Content);
Add parameters according to your needs. This work fine!
for my code, this works perfect.
// extention function for object->formed data body string
public static string toFormDataBodyString(this object src)
{
var res = new List<string>();
foreach (var key in src.GetType().GetProperties())
{
res.Add($"{key.Name}={src.GetType().GetProperty(key.Name)?.GetValue(src)}");
}
return string.Join("&", res);
}
//--------------------------------------
var data = new {
param1 = xxxx,
param2 = xxxx
}
var translateReq = new RestRequest("url_here")
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddParameter("application/x-www-form-urlencoded", data.toFormDataBodyString(), ParameterType.RequestBody);