Restsharp PUT custom header - c#

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

Related

Add content-type header while consuming API using GraphQL.client

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

Not able to add parameters to make GET request with C# RestSharp client

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!

RestSharp "Not found" response

I'm trying to use the Youtube Data API v3 with RestSharp. Problem is: I get the response: "Not found" when I try to send a request.
var client = new RestClient("https://www.googleapis.com/youtube/v3/channels?part=statistics");
var request = new RestRequest(Method.POST);
request.AddParameter("key", my api key);
request.AddParameter("id", my channel id);
request.AddParameter("fields", "items/statistics/subscriberCount");
IRestResponse response = client.Execute(request);
var content = response.Content;
Console.WriteLine(response.Content);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () { label1.Text = response.Content; });
This seems to be a problem with RestSharp or the code because in the Google API explorer thing you can test out the inputs and it works there.
I was trying the same thing today and was stuck on the same step. With an hour of effort I figured out.
In the RestClient(baseUri) constructor, just pass the base url and not the whole path.
While initializing RestClient(resource, Method), pass the path as resource and method will be the second parameter.

Setting Restsharp parameters

I've been going around in a circle with this. I am attempting to make a post with Restsharp. The problem is either I get an error about application/xml as the only allowed format or no content allowed in the prolog. In the below example if I use AddBody() then I will get the error about application/xml (in the watch for the request object I see the body is populated as text/xml), if I do the AddParameter() with ParameterType.RequestBody then I get the error about content in the prolog. I am having a hard time it seems controlling or even precisely what is being sent in the post.
var client = new RestClient("https://portfoliomanager.energystar.gov/wstest/");
var request = new RestRequest("{token}", Method.POST);
meterConsumptionType meteruse = new meterConsumptionType();
account newuser = new account();
// Populating object
request.AddHeader("Content-Type", "application/xml");
request.Parameters.Clear();
request.AddParameter("application/xml", newuser, ParameterType.RequestBody);
//request.AddBody(newuser);
request.AddUrlSegment("token", "account");
request.Parameters[1].ContentType = "application/xml";
IRestResponse response = client.Execute(request);
Add this line to change the serializer:
request.XmlSerializer.ContentType = "application/xml";

Restsharp XML request

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.

Categories

Resources