how to use restsharp web rest api - c#

hi there i am new to rest api
i build these api
https://dastanito.ir/test/ex2/api/storiesmaster/read.php
https://dastanito.ir/test/ex2/api/storiesmaster/read_one.php?id=60
i used requests lib in python and everything is ok
but i do not know how to use this with restsharp
var client = new RestClient("https://dastanito.ir/test/ex2/api/storiesmaster/read.php");
var request = new RestRequest("");
var response = client.Post(request);
MessageBox.Show(response.Content.ToString());

Based on RestSharp sample:
var client = new RestClient("https://dastanito.ir");
var request = new RestRequest("test/ex2/api/storiesmaster/read.php", Method.GET);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
Output:
{"StoriesMasters":[{"id":"2","story_code":"002a","master_code":"he3385_1"},{"id":"60","story_code":"001a","master_code":"he3385_1"},{"id":"3","story_code":"c57675","master_code":"ara3433_2"},{"id":"50","story_code":"d8885","master_code":"za76787_3"}]}

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

POST request in NET Core (C#) from python to C#

import requests
requests.post('https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start',
auth=('john#doe.com', 'secretPassword'))
How would one write this in C#? (NET Core)
Apart of the added comments, I would recommend using a library called RestSharp.
You can easily find the nuget package and the code will be as easier as:
var client = new RestClient("https://dathost.net");
client.Authenticator = new HttpBasicAuthenticator("john#doe.com", "secretPassword");
var request = new RestRequest("api/0.1/game-servers/{id}/start", Method.POST);
request.AddUrlSegment("id", "54f55784ced9b10646653aa9");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
You can also do async requests:
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
You can do it with HttpClient.
Add usings top of your code first.
using System.Net.Http;
using System.Net.Http.Headers;
And run this code wherever you want.
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("john#doe.com:secretPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await client.PostAsync(
"https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start", null);
Hope this helps.

Response on RestSharp with wrong charset(probably)

I have a server response, on a RestSharp client, and if i grab the response on PostMan it comes good:
Example: instalação
But when i call try this response on the RestSharp Client it comes like this:
Example: instala��o
the code:
{
var requestatt = new RestRequest("/mge/service.sbr?serviceName=CRUDServiceProvider.loadView", Method.POST);
// requestsharp.AddXmlBody(stringrequest);
requestatt.AddParameter("text/xml", bodyrequestatt, ParameterType.RequestBody);
requestatt.AddHeader("Content-Type", "text/xml;charset=ISO-8859-1");
IRestResponse responseatt = new RestResponse();
responseatt.ContentEncoding = "ISO-8859-1";
responseatt = client.Execute(requestatt);
}

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

Categories