Posting form submissions with the KOBO REST API - c#

I'm having a little trouble posting form submissions from C# to a KOBO Server (https://kf.kobotoolbox.org). The response I get is 'Bad Gateway'.
Here's my code:
var client = new RestClient("https://kc.kobotoolbox.org/api/v1/submissions");
//var client = new RestClient("https://kc.kobotoolbox.org/api/v1/forms/{pk}/labels");
client.Authenticator = new HttpBasicAuthenticator("a_user", "alpha9876");
//client.AddDefaultUrlSegment("pk", "31037");
//client.AddDefaultUrlSegment("tags", "tag1, tag2");
// client.AddDefaultUrlSegment("format", "xls");
//client.AddDefaultUrlSegment("url", "https://kc.kobotoolbox.org/api/v1/projects/1");
//client.AddDefaultUrlSegment("owner", "https://kc.kobotoolbox.org/api/v1/users/ona");
//client.AddDefaultUrlSegment("name", "project 1");
//client.AddDefaultUrlSegment("date_created", "2013-07-24T13:37:39Z");
//client.AddDefaultUrlSegment("date_modified", "2013-07-24T13:37:39Z");
var request = new RestRequest(Method.POST);
IRestResponse response = client.Execute(request);
request.AddHeader("header", "xml");
request.Resource = "C:\\Users\\Susan\\Desktop\\xmltest\\form_linkage_parentform.xml";
Could anyone help with a sample snippet of what the C# code for making this POST HTTP request would probably look like? Based on this: https://kc.kobotoolbox.org/api/v1/
Thank you!

I finally managed to do it using CSV files (https://kc.kobotoolbox.org/api/v1/forms) as follows:
var client = new RestClient("https://kc.kobotoolbox.org/api/v1/forms/{pk}/csv_import");
client.Authenticator = new HttpBasicAuthenticator("user_name", "password");
client.AddDefaultUrlSegment("pk", "31045");
string file_path = Server.MapPath("~/myform.csv");
var request = new RestRequest(Method.POST);
request.AddFile("csv_file", file_path);
IRestResponse response = client.Execute(request);

Related

How to call API in asp.net MVC

I want to create a summary page for Covid-19 cases. I found this API : CORONAVIRUS COVID19 API
var client = new RestClient("https://api.covid19api.com/live/country/south-africa/status/confirmed/date/2020-03-21T13:13:30Z");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
My question is: how I can call/get the methods on this API using ASP.NET MVC?
And please note that I'm a beginner
Thanks
This code would allow you to get the data from the Uri you provided above:
var c = new HttpClient();
var r = await c.GetAsync("https://api.covid19api.com/live/country/south-africa/status/confirmed/date/2020-03-21T13:13:30Z");
var json = await r.Content.ReadAsStringAsync();

How to capture Json from web site using c#

I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True
I'd like to collect JSON response using C#
Below is my horrible code
string cookie = "my super secret cookie string";
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent","Mozilla/5.0");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";
request.AddParameter("cookie", cookie, ParameterType.Cookie);
var client = new RestClient(url);
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
How can I get it to return JSON to me? I am getting something but not the JSON I want
Try updating your Access header to application/json.
request.AddHeader("Accept", "application/json");
Accept indicates what kind of response from the server the client can accept.
You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context
After poking around for a bit I figured it out. For the benefit of all:
private bool FinancialStatement(string symbol, string statement, string period)
{
var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";
var client = new RestClient(target);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", MACHINE_COOKIE);
IRestResponse response = client.Execute(request);
dynamic responseObj;
try
{
responseObj = JsonConvert.DeserializeObject(response.Content);
}
catch (Exception)
{
return false;
}
return response.IsSuccessful;
}

My POST request fails in c# but works perfectly fine in POSTMAN

I make a login request to a nextcloud installation installed locally on my server.
I pass 3 parameters: requesttoken, password, shareToken. The request works perfectly fine in postman but fails in my C# code.
I get the following reponse
with a 412 status code.
"{\"message\":\"CSRF check failed\"}"
I copy pasted the c# code derived from my postman request which is like below. Any clues?
var client = new RestClient("https://nextcloud.xxxx.org/index.php/s/Sryt58drbe34/authenticate/showShare");
var request = new RestRequest(Method.POST);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "requesttoken=oq%2Fqo4Nx0eNvYyty5QNeJqPbjZxMCtn3bFvUfEi%2Fwcg%3D%3AlOWrxPECsptWMBwGnTYMQ%2FG3yPENe7iQQwz7EQOLmYA%3D&password=bb9AYoqWSmAxiCgvFusW&sharingToken=Sryt58drbe34", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Your post should be something like this
var uri = "https://nextcloud.xxxx.org/index.php/s/Sryt58drbe34/authenticate/showShare"
var requestToken= "oq/qo4Nx0eNvYyty5QNeJqPbjZxMCtn3bFvUfEi/wcg=:lOWrxPECsptWMBwGnTYMQ/G3yPENe7iQQwz7EQOLmYA=";
var password = "bb9AYoqWSmAxiCgvFusW";
var shareToken = "Sryt58drbe34";
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("requesttoken", requestToken),
new KeyValuePair<string, string>("password", password ),
new KeyValuePair<string, string>("sharetoken ", shareToken )
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

Using RestSharp with Gerrit REST API

I want to use RestSharp to issue Api calls to Gerrit but I'm having trouble with authentication.
For example there is the curl command which works:
curl --digest --user VladDracul:5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA http://localhost:8080/a/groups/
but how can I give the --user to a restSharp call?
myAuth = new HttpBasicAuthenticator("VladDracul","5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");
restClient = new RestClient(BaseUrl);
restClient.Authenticator = myAuth;
var request = new RestRequest(Method.GET);
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");
var response = restClient.Execute(request);
The response I get is "Unauthorized"
I found the answer. Adding the line gets it working.
var request = new RestRequest(Method.GET);
request.Credentials = new NetworkCredential("VladDracul", "5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");;
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");

Cannot set MIME type using RestSharp and GoCardless

Using C#, .Net 4,5, RestSharp v4.0.3
Attempting to create an api_key in GoCardless
I create a RestClient like this:
var client = new RestClient();
client.BaseUrl = SandboxBaseUrl;
client.Authenticator = new HttpBasicAuthenticator(apiKeyId, apiKey);
client.AddDefaultHeader("GoCardless-Version", Properties.Settings.Default.GoCardlessVersion);
client.AddDefaultHeader("Accept", "application/json");
client.AddDefaultHeader("content-type", "application/json");
request.AddHeader("content-type", "application/json");
When I post to GoCardless I get the error
{"error":{"message":"'Content-Type' header must be application/json or application/vnd.api+json ......
After a lot of fruitless searching I gave up and used the solutions in older StackOverflow postings. Such as
// Create the Json for the new object
StringBuilder requestJson = new StringBuilder();
var requestObject = new { api_keys = new { name = name, links = new { role = role } } };
(new JavaScriptSerializer()).Serialize(requestObject, requestJson);
...
// Set up the RestSharp request
request.Parameters.Clear();
request.AddParameter("application/json", requestJson, ParameterType.RequestBody);
I can see why this works - and even perhaps the intention of RestSharp doing it this way.

Categories

Resources