request webapi with restharp - c#

Goodmorning everyone,
using postan I make a request as in the figure, and I get data.
I write using the same call (at least I assume) and it returns an empty string and not a json.
Where could it be the mistake?
Thank you all
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY", Method.POST);
// request.RequestFormat = DataFormat.Json;
request.AddParameter("TblName", "STSIG$");
var response = client.Execute(request);
var content = response.Content;
enter image description here

Query Parameter Detail is mentioned in add Parameter. Please change the code as below
Code:
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY?TblName=STSIG$", Method.POST);
//Request Body detail needs to be added.
//I assumed input is JSON. Please change the header part , if the body has different
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content;

Related

Restsharp Request gives "Argument 1: cannot convert from 'RestSharp.Method' to 'string?'" error

I am trying to call POST API request using restSharp 108.0.1v.
The code is as below;
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles");
var request = new RestRequest(Method.Post);
request.AddHeader("x-api-key", "MYAPIKEY");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n\t\"registrationNumber\":\"AA19AAA\"\n}", ParameterType.RequestBody);
RestResponse response = client.Execute(request);
The snippet Method.Post of var request = new RestRequest(Method.Post);gives the error that I mentioned.
Please help me to solve this issue ?
Looking at the documentation here the first parameter of the RestRequest constructor is the subpath to the resource you want to access. Instead you should do something like the following
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk");
var request = new RestRequest("vehicle-enquiry/v1/vehicles", Method.Post);
// ... or I believe this should work as well:
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1");
var request = new RestRequest("vehicles", Method.Post);

Sending parameter request with RestSharp in C#. Getting Error: Required field \"expr\" missing in JSON body

I am writing a simple calculation machine application in Windows Form application. I want to perform operations using math js web api (post), but where I call api I get this error:
Error: Required field \"expr\" missing in JSON body" // in Response
My code is here :
private void Equals_Click(object sender, EventArgs e)
{
var client = new RestClient("http://api.mathjs.org/v4/");
var request = new RestRequest("/expr", Method.POST);
var deger = txtCevap.Text; // txtCevap.Text is my calculator parameter
var json = JsonConvert.SerializeObject(deger);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
}
Can you help me in this topic? Thanks.
for api.mathjs.org, you are required to pass string or string[] with expr element. Please review their requirements here.
var client = new RestClient("http://api.mathjs.org/v4/");
var request = new RestRequest("", Method.POST);
var deger = #"{""expr"": ""2+1""}"; // txtCevap.Text is my calculator parameter
request.AddJsonBody(deger);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
response object's content looks like below that you can easily deserialize. they always have Result and Error.
"{\"result\":\"3\",\"error\":null}"
dynamic result = JsonConvert.DeserializeObject(response.Content);
string answer = result["result"].ToString()

Get Pdf Rest Sharp (GET)

I am testing a service to which you send a json and it returns a PDF with the data you sent it. I did tests with Insomnia as shown here:
It works correctly, but trying to recover the file through code always generates an error. My code is the following:
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\n\t\"QuotationId\": 0,\n\t\"QuotationName\": \"CasaLomas\",\n\t\"UserGUID\": \"75DB06AC-E349-4C47-A5AF-87EC63A9B8A9\",\n\t\"QuotedQuantity\": 5,\n\t\"TotalPrice\": 500,\n\t\"CopyEmail\": \"angelmg50#hotmail.com\",\n\t\"MaterialDetails\": [\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t}\n\t]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This connects correctly with the API but apparently the json has not been sent correctly. Any idea why this happens?
I created the json with dynamic and tried to send it.
dynamic cotizacion = new JObject();
cotizacion.QuotationId = 0;
cotizacion.QuotationName = "Casa lomas 3";
cotizacion.UserGUID = "75DB06AC-E349-4C47-A5AF-87EC63A9B8A9";
cotizacion.QuotedQuantity = 6;
cotizacion.TotalPrice = 456.12;
cotizacion.CopyEmail = "angelmg50#hotmail.com";
cotizacion.MaterialDetails = new JArray(new JObject(
new JProperty("SKU", "C05423082015140001"),
new JProperty("Name", "PORC KONE WHITE MATE 60x30x1"),
new JProperty("Quantity", 1),
new JProperty("Price", 638.09),
new JProperty("Amount", 6380.30)));
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", cotizacion, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
But this does not work either.
When I print response.Content in console it shows me the following: "Message": "Internal error when trying to generate the PDF" Value can not be null. \ R \ nParameter name: source "," StatusCode ": 3," Result ": null, "ResultList": null}
https://github.com/restsharp/RestSharp/wiki/Recommended-Usage
It seems like you are trying to add a parameter with the name "application/json". You may need to specify the name of the parameter in the endpoint and use AddObject instead of AddParameter. We can help more if you can give us some more info on your endpoint.

Use RestSharp Post Object as JSON and read it from the other side of the call

I have a C# REST Web API and I have some code like this that makes a request to an endpoint. Some of the data that I want to pass along is an object of my own type and since it is a complex object, I would like to pass it using POST.
RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint)
{
Timeout = 1000
};
string requestResource = Constants.Endpoints.apiEndPoint;
RestRequest request = new RestRequest(requestResource, Method.POST);
request.AddParameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.AddParameter("id", id, ParameterType.UrlSegment);
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
On the other side, I am trying to read the object itself with some code like this
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var content in provider.Contents)
{
// what should I do here to read the content as a JSON
// and then transform it as the object it used to be before the call?
}
I tried to do await content.ReadAsJsonAsync< MyType>(); but also tried await content.ReadAsStringAsync(); and none of these worked. Am I doing something wrong at the time I execute in the client? Or is it something that I am doing on the other side while reading the content?
Instead of this line:
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
You should use the .AddBody(object) method.
So you're code would look like this:
RestRequest request = new RestRequest(requestResource, Method.POST);
//add other headers as needed
request.RequestFormat = DataFormat.Json;
request.AddBody(objectIWantToSerialize);
IRestResponse response = client.Execute(request);
On the server, if you're using MVC/WebAPI, you can just put the C# type as the input and ASP.NET will deserialize it for you. If not, can you provide more context about how you're receiving the request?

GoToWebinar - Request not in expected format - RestSharp

Similar to this forum post:
https://developer.citrixonline.com/forum/request-not-expected-format
However he didn't really explain what he found was wrong with his code.
I'm using RestSharp to make API calls. I've been able to get it to work great to pull an list of upcoming webinars however when I try to register participant I keep getting a 400/Request not in expected format error.
Following this documentation https://developer.citrixonline.com/api/gotowebinar-rest-api/apimethod/create-registrant, here is my code:
var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants", "300000000000xxxxxx", btn.CommandArgument));
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddHeader("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
request.AddParameter("firstName", LoggedInUser.FirstName);
request.AddParameter("lastName", LoggedInUser.LastName);
request.AddParameter("email", LoggedInUser.Email);
var response = client.Execute(request);
var statusCode = response.StatusCode;
Any insights on how I can figure out why I keep getting that error?
Thank you!
Instead of using AddParamter (which adds key/value parameters to the request body), you need to write JSON instead:
request.DataFormat = DataFormat.Json;
request.AddBody(new {
firstName = LoggedInUser.FirstName,
lastName = LoggedInUser.LastName,
email = LoggedInUser.Email
});
You'll also need to clear the handlers (which automatically set the Accept header) if you want to specify them directly:
client.ClearHandlers();

Categories