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;
}
Related
I am new to WEB API and I have created a get and a post method the get is working however the the parameter in the post is returning null.
The code for request is
if (ModelState.IsValid)
{
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var test = JsonConvert.SerializeObject(order);
request.AddJsonBody(order);
IRestResponse response = client.Execute(request);
and it points to the following method
[HttpPost]
[Route("api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody]IOrder order)
{
if(order== null)
{
var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The order is a required parameter"),
ReasonPhrase = "Order not present"
};
throw new HttpResponseException(resp);
}
I have added the <requestLimits maxAllowedContentLength="4294967295" /> to the web config but to no avail.
Can anyone point me to what I am doing wrong with the request?
Cheers
Try this code
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
var body = JsonConvert.SerializeObject(order);
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
and never use interfaces in action parameters, since the action needs to create an object, but it is impossible from interface
[Route("~/api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody] Order order)
I think if can rewrite you request to this ->
var client = new RestClient("/api/order/createorder",Method.Post, DataFormat.Json);
client.AddJsonBody(order);
IRestResponse response = client.Execute(request);
That might just work, you may need some mapping potentially if the payload you are passing to the controller is a different type.
Basically, I've been trying to authenticate through oauth2 on c# using restsharp, but I am receiving a bad request response, I'm not sure if it's something related to the API configuration or if it's something I'm missing In my code.
public string getToken(string email, string password)
{
var restclient = new RestClient(loginUrl);
RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("email", HttpUtility.UrlPathEncode(email));
request.AddParameter("password", HttpUtility.UrlPathEncode(password));
request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
this is the response when I execute that code
An this is the postman execution
Thanks!
I think there problem with adding parameters the way you are adding.
latest restsharp support this,
Also,avoid encoding of params by setting to false
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test#test.com",false);
var restclient = new RestClient(loginUrl); I think you need to check your url.
Try this.. you OAuth is password grantype are your sure your not missing any credentials like client_id, scope and client_secret.
public static string getAccessToken(string usern, string pswd)
{
RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
RestRequest request = new RestRequest() { Method = Method.GET};
request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", usern, ParameterType.GetOrPost);
request.AddParameter("password", pswd, ParameterType.GetOrPost);
IRestResponse response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
I subscribed to Computer Vision API on RapidAPI. When I'm testing the API on the RapidAPI platform, it's working perfectly. But when I'm calling it from my app, it responding 400 Bad request.
How can I fix this problem?
I'm using the RESTSharp library.
Here's my code -
public static IRestResponse GetClassifiedImageData()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return client.Execute(request);
}
And if I call asyncronusly, I get this message -
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,ComputerVision.Program+d__2]
Async Code-
public static async Task<IRestResponse> GetClassifiedImageData2()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
I've tried these -
Restarting Visual Studio.
Cleaning Temp and prefetch files.
Based on my test, it is the URL encoding that is causing the problem.
You may use the code sample from Rapid API website. However, while using RestClient, you should not urlencode the urlpath. The Rapid API engineer may make a mistake here. In most case, a , character does not need to be urlencoded. So, you can directly use https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description as the path string.
And, anyway, the correct encoded string is https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription
The code sample from Rapid API:
I used the sample, and got the same error message as yours. But I solved it by using the original string or the correct encoded string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// The correct encoded string will work
//var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription");
// The original string will work
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
static void Main(string[] args)
{
var result = GetClassifiedImageDataAsync().GetAwaiter().GetResult();
Console.WriteLine(result.Content);
}
And you can also use RestClient's method to add query string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// Without query string
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze");
var request = new RestRequest(Method.POST);
// Add as query string manually
request.AddParameter("visualfeatures", "Categories,Tags,Color,Faces,Description", ParameterType.QueryString);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
And the successful result:
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);
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.