Setting Restsharp parameters - c#

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

Related

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, Basic Auth

I have a question about making an authorized call to a GET Url using RestSharp.
I have a provided basic token, which looks something like this: dGVzdG5hbWU6dGVzdHBhc3N3b3Jk.
Let's say the GET Url is: https://sometest.api.com/todos?id=1 and requires authorization.
How would I pass the above token in the above GET Url?
I tried this:
var client = new RestClient("https://sometest.api.com") // base address
var request = new RestRequest("todos?id=1"); // resource
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic dGVzdG5hbWU6dGVzdHBhc3N3b3Jk");
var response = client.Execute(request);
This does not seem to work. Do I need to add the basic token as a parameter instead, or both in the header and as parameter?
Or would I need to use the client.Authenticator on the RestClient:
client.Authenticator = new HttpBasicAuthenticator("testname", "testpassword");
Any help is appreciated, thanks.
Best Regards
Could you provide more information how did you conclude that it does not work? Any exception? An error message you could provide?
How did you get that token? What the expiration time of the token?
This is how I am doing it, pretty much like you, except I am using different token type:
var request = CreateServerRequest(_configuration.SOME_URI);
request.AddHeader("Authorization", $"Bearer {Token}");
request.AddJsonBody(request);
var server = new RestClient(_configuration.SOME_ENDPOINT);
var serverResponse = server.Execute(request);
if (serverResponse.StatusCode == HttpStatusCode.OK)
{
return new ServiceResponse<bool>(true);
}
Where the method CreateServerRequest contains only:
return new RestRequest(uri)
{
RequestFormat = DataFormat.Json,
Method = Method.POST
};
Hope this helps,
Cheers and happy coding.

How to add json to RestSharp POST request

I have the following JSON string that is passed into my c# code as a string parameter - AddLocation(string locationJSON):
{"accountId":"57abb4d6aad4","address":{"city":"TEST","country":"TEST","postalCode":"TEST","state":"TEST","street":"TEST"},"alternateEmails":[{"email":"TEST"}],"alternatePhoneNumbers":[{"phoneNumber":"TEST"}],"alternateWebsites":[{"website":"TEST"}],"auditOnly":false,"busName":"593163b7-a465-43ea-b8fb-e5b967d9690c","email":"TEST EMAIL","primaryKeyword":"TEST","primaryPhone":"TEST","rankingKeywords":[{"keyword":"TEST","localArea":"TEST"}],"resellerLocationId":"5461caf7-f52f-4c2b-9089-2ir8hgdy62","website":"TEST"}
I'm trying to add the JSON to a RestSharp POST request like this but it's not working:
public string AddLocation(string locationJSON)
{
var client = new RestClient(_authorizationDataProvider.LocationURL);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", _authorizationResponse.Token);
...
request.AddJsonBody(locationJSON);
var response = client.Execute(request);
}
The response comes back as "Bad Request". Here is what I get if I inspect the response in the debugger:
{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}}
I have inspected the request parameters after calling AddJsonBody and the value appears to be including the escape sequence for double quotes - which seems to be the issue.
{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"}
so my question is how do I add a json string to the request body?
I've ran into this problem as well. Try something like this instead of AddJsonBody.
request.AddParameter("application/json", locationJSON, ParameterType.RequestBody);
This should work:
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(yourObject), ParameterType.RequestBody);
If you directly add the serialized object, the problem is the Json convert is adding "\" before each ".
I have tried like this and it working fine, Add Bearer with token
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer " + "your token key");
request.AddHeader("accept", "application/json");

How do I use RestSharp to POST a login and password to an API?

I'm trying to write a C# application that will call an api for Pacer.gov. First thing I need to do it get a cookie to pass with my request. I'm using Chrome's Postman app to try to generate a POST request. Can someone explain what I'm doing wrong?
The instructions I got from Pacer.gov to get the authentication token are
For credentials, you can POST username(loginid) and password(passwd) to the authentication service here https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl
This will issue you a PacerSession cookie.
Here are some ways I tried:
(I’m just showing ##### as the login and ***** as the password, but I used the actual login and password when I tried it)
Including username and password in the URL
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-in/check-pacer-passwd.pl?loginid=#####&passwd=*****");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "a5bd0d9c-85f5-4ed6-6ad8-ac06e553f5db");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the header
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "add9dedf-10bf-eab4-428a-134c0e8a1783");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("passwd", "*****");
request.AddHeader("loginid", "#####");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the body as form data
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "454a8ebd-b2b4-3db2-0c5c-c48e2964c671");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"loginid\"\r\n\r\n#####\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"passwd\"\r\n\r\n*****\r\n-----011000010111000001101001--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
o Received message “Could not get any response”
Typing URL into Chrome with the username and password
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
o Received error “This site can’t be reached”
UPDATE - 5-31-16
I've made several more attempts, but am still not getting the cookie back. I tried this code:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
When I look at the response, there is one cookie called JESSIONID which appears just to be a generic browser session ID, not the authentication code I'm expecting:
I'm not exactly sure what to expect from the response, but I know that a "NextGenCSO cookie" was mentioned in one of the e-mails from Pacer. If I login through the web browser and look at the cookies, I see a NextGenCSO cookie; I'm guessing I should be seeing something similar in the response from the API call:
UPDATE - 6-3-16
Thanks to help from #jonathon-reinhart, I was able to get the authentication cookie working with this code:
// Authentication
var client = new RestClient("https://pacer.login.uscourts.gov");
client.CookieContainer = new System.Net.CookieContainer();
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
var PacerSession = "";
foreach (RestResponseCookie cookie in response.Cookies)
{
if (cookie.Name == "PacerSession")
{
PacerSession = cookie.Value;
}
}
You are not correctly POSTing as the directions indicate.
Putting this:
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
into the address bar is not a POST. That's a GET with query string parameters.
See the RestSharp homepage for an example on how to POST:
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
You want to include loginid and passwd as data ("parameters" as RestSharp calls them), not has headers.
So you should be instead doing something like this:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "####");
request.AddParameter("passwd", "****");
IRestResponse response = client.Execute(request);

Restsharp PUT custom header

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

Categories

Resources