I'm trying to PUT some data over an API with restsharp.
From the manual of the API, the PUT call is made using:
template params
id string
barcode string
and
query params
a string
operator string
c long
The request should have a custom header: Name = “Content-Type” Value = “application/xml”
Can someone tell me how to use restsharp to post a request like this?
Rest Sharp Put Custom Header, this helped me a lot the construction is like
request.RequestFormat = RestSharp.DataFormat.Xml;
request.XmlSerializer = newRestSharp.Serializers.DotNetXmlSerializer();
request.AddBody(x);
was not working. But when I changed the code block body to
request.RequestFormat = RestSharp.DataFormat.Xml;
request.AddParameter("text/xml", x, ParameterType.RequestBody);
my solution began to work properly.
var client = new RestSharp.RestClient();
var request = new RestRequest(myUrl);
request.RequestFormat = DataFormat.Xml;
Should cause the content type and serialization to work correctly.
Related
I'm trying to make a GET request to a REST api which returns a JSON. This is what I have right now:
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync<MyDtoClass[]>(request);
When this code executes, response is an array of MyDtoClass but the fields in each element of the array are null. If instead, I run this code (I removed the generic):
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync(request);
then response is a string represintation of the JSON that BASE_URL + CONTROLLER_PATH returns (nothing is null).
What is the idiomatic way to make a request to this REST api and convert the response into an array of MyDtoClass. Also, if anyone has suggestions for a library you think is better then RestSharp, please share.
Thank you in advance.
The issue was that MyDtoClass had fields instead of properties.
I am using GraphQL.client Nuget package to call the Graphql API which requires Content-Type header.
Following is what I am doing
Set GraphQL options. Note I have set options.MediaType
GraphQLHttpClientOptions options = new GraphQLHttpClientOptions();
options.MediaType = "application/json";
options.EndPoint = new Uri( "https://sample.api.com/graphql");
Initialize the client and Authorization header
var graphQLClient = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());
graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "JWT <token>");
GraphQL query
var projectsQuery = new GraphQLRequest
{
Query = #"
query {
projects {
name
}
}"
};
Invoke the API and retrieve the response results
var graphQLResponse = await graphQLClient.SendQueryAsync<ProjectResponse>(projectsQuery);
var projects = graphQLResponse.Data.Projects;
However I am getting Bad request with error "{"errors":[{"message":"Must provide query string."}]}"
What am I doing wrong here? How do I set the content-type header correctly. I tried adding the content-type header as below but it does not allow giving the
Misused header name. Make sure request headers are used with
HttpRequestMessage, response headers with HttpResponseMessage, and
content headers with HttpContent objects.
graphQLClient.HttpClient.DefaultRequestHeaders.Add("content-type", "application/json");
I tried searching for a solution but did not find one. The same request works when I pass content-type header in the request headers via Postman client.
Does anybody have any pointer on the same?
If anyone is still looking for answer, please find below.
var graphQLClient = new graphQLHttpClient("https://www.example.com/graphql", new NewtonsoftJsonSerializer());
graphQLClient.HttpClient.DefaultRequestHeaders.Add("key", "value");
Please mind the HttpClient in graphQLClient.HttpClient.DefaultRequestHeaders.Add("key", "value");
This is my first time working with APIs and I'd really appreciate your help and patience on bearing with me.
I'm making a GET request to the client Synccentric for getting data [Given URL below I'm using for ref].
https://api.synccentric.com/?version=latest#cb8d3255-7639-435e-9d17-c9e962c24146
[Update]
I found a way to attach parameters to querystrings and the response was validated. I'm still stuck with passing the array of fields.
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", 1);
request.AddParameter("downloadable_type", "csv");
string[] fields = new[] { "asin", "upc", "actor", "all_categories", "is_eligible_for_prime", "listing_url" };
request.AddParameter("fields", fields);
IRestResponse response = client.Execute(request);
I think I know where the problem is
So the [5]th parameter should ideally hold this value "[\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]"
But instead it looks like this.
Can you guys help me with this?
I tried the API call using Python and referencing the documents and I did get the desired response.
Attaching the python block below:
import requests
url = 'https://v3.synccentric.com/api/v3/products'
payload = "{\n \"campaign_id\": 12618,\n \"fields\": [\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]\n} #\"downloadable\":1,\n \"downloadable_type\":\"csv\"\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {{MyAPIToken}}'
}
response = requests.request('GET', url, headers = headers, data = payload, timeout= 100000 , allow_redirects= 0)
print(response.text)
After the execution I got the response I was looking for.
RestSharp will not allow you to send a GET request with a content-body. The error says it all.
You will have to send the parameters as query parameters.
Console.WriteLine("**** Starting Synccentric API Fetch ****");
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
Console.WriteLine("**** Adding parameters ****");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", "true");
request.AddParameter("downloadable_type", "CSV");
var fields = new[] { "asin", "upc", "actor", "all_categories" };
foreach (var field in fields)
{
request.AddParameter("fields", field);
}
IRestResponse response = client.Execute(request);
This will build you the following query string, which should be sent and hopefully understood okay.
https://v3.synccentric.com/api/v3/products?campaign_id=12618&downloadable=True&downloadable_type=CSV&fields=asin&fields=upc&fields=actor&fields=all_categories
UPDATE Having looked at the comments, it may be that RestSharp cannot be used with that API as it seems that it requires content body with a GET request!
I've a problem as I need to send some json to a url. When I send all my json and token to the page.
Then there will be no content JSON value into the system.
I have checked up on whether there is some content and it is there, but it sends just do not like json values.
string apiKeyToken = model.reepaytoken; // TOKEN HERE.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
When I blow my json looks like this.
[HttpPost]
public ActionResult information(BuyMedlemskabViewModel model)
{
DataLinqDB db = new DataLinqDB();
var Pric = db.PriceValues.FirstOrDefault(i => i.id == model.HiddenIdMedlemskab);
if (Pric != null)
{
string _OrderValue = DateTime.Now.Year + Helper.Settings.PlanValue();
Session[HelperTextClass.HelperText.SessionName.OrderId] = _OrderValue;
Session[HelperTextClass.HelperText.SessionName.FakturaId] = model.HiddenIdMedlemskab;
Session[HelperTextClass.HelperText.SessionName.fornavn] = model.Fornavn;
Session[HelperTextClass.HelperText.SessionName.efternavn] = model.Efternavn;
Session[HelperTextClass.HelperText.SessionName.Adresse] = model.Adresse;
Session[HelperTextClass.HelperText.SessionName.Post] = model.Postnr;
Session[HelperTextClass.HelperText.SessionName.Byen] = model.Byen;
Session[HelperTextClass.HelperText.SessionName.Mobil] = model.Mobil;
string apiKeyToken = model.reepaytoken;.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
}
return RedirectToAction("information");
}
EDIT - Update (ERROR HERE):
ReePay API reference: https://docs.reepay.com/api/
I think there are a few things, you'll have to fix:
First of all you're obviously trying to create a ressource (usually a POST or PUT, speaking in REST-words but you're using WebClient's DownloadString-method which performs a GET. So I think you should probably use a POST or PUT instead but which one to chose exactly depends on the web service you're contacting.
Then you seem to have mistaken the Content-Type-header and tried to pack the payload in there. The payload - your customer JSON - will have to be put into the request's body.
Based on your previous questions I assume the service you're trying to contact is either PayPal or QuickPay. To further help you with this question, it'd be helpful if you could specify which one you use.
If it's QuickPay, please notice that there's an official .NET client which you could use instead of using WebClient on you own.
But anyway for making HTTP requests I'd suggest you to use HttpClient in favor of WebClient. You'd generally do it in a way like this:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post,
APIClassPay.HelperPay.CreateCustomerURL);
request.Headers.Add("X-Auth-Token", apiKeyToken);
request.Headers.Add("Content-Type", "application/json");
request.Content = new StringContent(JSONCustomer);
var response = await httpClient.SendAsync(request);
}
EDIT:
As you clarified in a comment, the service you're using is Reepay. If you take a look at the documentation of the create customer method, you can see, that the necessary HTTP method is POST. So the code snippet above should generally fit.
Regarding the compilation error you faced, I updated the code-snipped above. There was a mistake in the variable names I chose. Please note, that you dropped the keyword await as I can see from your screenshot. Please re-enter it. If the compiler complains about it, it's very likely that the .NET framework version of your project is less than 4.5 which is necessary to use async/await.
So you should update your project's .NET framework version at best to version 4.6.1 as Microsoft recently announced that support for 4.5 and others is discontinued. Have a look here on how to do that.
I have to use RestSharp to PUT some data into an API.
The API resource is: /clients/services/finances/{finances-id}/subcategory/{subcategory-id}
Apart from template parameters, there are some query parameters:
organization-id (string)
operator-id (string)
And also, the request Content-Type must be application/xml
The way I'm trying to create this PUT request using RestSharp:
RestClient client = new RestClient(url);
client.Authenticator = Auth1Authenticator.ForRequestToken(Config.getVal("api_key"), Config.getVal("secret_key"));
IRestRequest request = new RestRequest("", Method.PUT);
request.RequestFormat = DataFormat.Xml;
request.AddParameter("organization-id", Config.getVal("params.org"));
request.AddParameter("operator-id", "Accounting");
IRestResponse response = client.Execute(request);
But I'm only get HTTP Status 415 - Unsupported Media Type
Can you please help me to resolve this. GET request is working like a charm.
Try sending your request body like this:
request.XmlSerializer = new RestSharp.Serializers.XmlSerializer();
request.RequestFormat = DataFormat.Xml;
request.AddBody([new instance of the object you want to send]);
Also, are you sure that the URL you're accessing is correct (i.e. have the placeholders been filled with your params)?
Alternatively you can try doing this:
request.AddParameter("text/xml", [your object to serialize to xml], ParameterType.RequestBody);
You might also try and make your example as similar to the restsharp wiki example as possible to make it work:
https://github.com/restsharp/RestSharp/wiki/Recommended-Usage