Reputation: 185
I just created a HTTP get request to get the content (All the Badges) from Stack Overflow for my console application as shown below :
public void getStackBadges()
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.stackexchange.com/docs//badges?order=desc&sort=rank&site=stackoverflow");
var res = client.GetAsync(client.BaseAddress).Result;
Console.WriteLine(res);
}
Can anybody please tell if I want to get all the badges from stack overflow using this API what I need to do. I don't really understand the format of result that I am getting on my Cmd prmt !
Output on Console:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Credentials: false
X-Content-Type-Options: nosniff
Cache-Control: private
Date: Thu, 28 Dec 2017 09:49:33 GMT
Content-Length: 880
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
}
Upvotes: 0
Views: 98
Reputation: 8597
You're querying the documentation of the API and you're most likely getting the page markup.
You should be querying: https://api.stackexchange.com/2.2/badges?order=desc&sort=rank&site=stackoverflow
The format of the output in above API method is JSON.
Few things to note in the output:
To change the page you append a &page=
parameter to the url.
So your query for page 2 would look like this:
https://api.stackexchange.com/2.2/badges?page=2&order=desc&sort=rank&site=stackoverflow
Edit:
As I said, the API I have linked is correct, your problem is the way you try to display the content of the response from the API.
.Result
is not what you think it is. .Result
returns Task<TResult>
which is not the response from the API but the result of the request. That's why you have status code of the request, response type, etc etc.
Here's how to retrieve the response text. This is a sample, you'll need to do your own processing if you want to access different properties of the response objects. This is a separate question though and it's outside the scope of this one.
var response = client.GetAsync("https://api.stackexchange.com/2.2/badges?order=desc&sort=rank&site=stackoverflow").Result;
string res = "";
using (HttpContent content = response.Content)
{
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
Upvotes: 4