C# Send data with method POST to API - c#

Dont know what i doing wrong, need to fill database with datas from my VSTO Outlook Addin.
jObjectbody.Add( new { mail_from = FromEmailAddress }); mail_from is name of column in database, FromEmailAddress is value from my Outlook Addin
How to send to API https://my.address.com/insertData correctly ?
RestClient restClient = new RestClient("https://my.address.com/");
JObject jObjectbody = new JObject();
jObjectbody.Add( new { mail_from = FromEmailAddress });
RestRequest restRequest = new RestRequest("insertData", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("text/html", jObjectbody, ParameterType.RequestBody);
IRestResponse restResponse = restClient.Execute(restRequest);
error : Could not determine JSON object type for type <>f__AnonymousType0`1[System.String].
If i try this in Postman (POST->Body->raw->JSON) data are strored in database, except dont use value just data.
{
"mail_from":"email#email.com"
}
thanks for any clue achieve success

You can use restRequest.AddJsonBody(jObjectbody); instead of AddParameter (which I believe adds a query string).
See the RestSharp AddJsonBody docs. They also mention to not use some sort of JObject as it wont work, so you will probably need to update your type as well.
The below might work for you:
RestClient restClient = new RestClient("https://my.address.com/");
var body = new { mail_from = "email#me.com" };
RestRequest restRequest = new RestRequest("insertData", Method.POST);
restRequest.AddJsonBody(body);
IRestResponse restResponse = restClient.Execute(restRequest);
// extra points for calling async overload instead
//var asyncResponse = await restClient.ExecuteTaskAsync(restRequest);

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);

How do i get the response from a post request? Restsharp

I have tried looking for the answer but i cant find it if you can please help
var options = new RestClientOptions("https://httpbin.org/#/HTTP_Methods/post_post")
{
ThrowOnAnyError = true,
Timeout = 1000
};
var client = new RestClient(options);
var request = new RestRequest()
.AddQueryParameter("foo", "bar");
Im using RestSharp 107.3.0 please help if you can
Use .Result which will give response from both Get and Post method in RestSharp 107.
RestClient client = new("http://baseURL");
RestRequest restRequest = new("api/test");
restRequest.AddQueryParameter("foo", "bar");
RestResponse response = client.ExecuteAsync(restRequest, Method.Post).Result;
Assert.AreEqual(HttpStatusCode.OK, response);

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?

my webservice restful client fail post c# bearer

I Write one application to access one Webservice Restful using C#, i get the Token with success, i access other services without parameters fine, but when i need to send parameters in POST method it´s not work.
In other side, the Wesbservice dont see my post.
Can someone help-me about this ?
Here is my code.
string urlMethod = metodo;
// "/api/v1/organizacao/criar";
var accessToken = IntegraPb.GetToken();
var client = new RestClient(Sincronizador.Properties.Settings.Default.apiUrl);
var request = new RestRequest(urlMethod, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + accessToken);
var jsserie = new System.Web.Script.Serialization.JavaScriptSerializer();
// obj is my class to serialize
request.AddJsonBody(jsserie.Serialize(obj));
IRestResponse response = client.Execute(request);
This image is the request object
AddJsonBody receives a object, not a serialized string of your object. It does the serialization internally.
So use this instead:
request.AddJsonBody(obj);

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