I recently had the need to use the Stack Overflow API in a web project and it took me a while so I thought I’d capture what I learnt.
The Stack Overflow API
Stack Overflow have a really nice REST API. It lets you get to pretty much any information in Stack Overflow and is really well documented.
The API follows the usual pattern of OAuth authentication. You register your application, get a key and then follow the usual OAuth Authentication procedure.
The nice thing about the API is that a lot of the methods do not require authentication and you can access them with a simple, unauthenticated GET request. You can see all the methods and whether authentication is required here: http://api.stackexchange.com/docs.
There are request limits and other restrictions for unauthenticated apps, but you can do things like search for unanswered questions without authentication.
GZIP and DEFLATE
The one thing about the API which took me a while to figure out is that the API uses GZIP or DEFLATE compression by default.
This means that if you call the API as usual, you will get what looks like a corrupted response. In debug, it will look something like this because the response is not being uncompressed in your code:
How to Call the API and decompress the response
The solution to this is actually really simple and I discovered it in this Stack Overflow thread (in the comments of the main answer).
You have to create a
HttpClientHandler, set the
AutomaticDecompression property. You then use that to create your
HttpClient as usual.
This is my complete c# code that uses the Search function to get unanswered questions on ASP.NET
HttpClientHandler handler = new HttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var httpClient = new HttpClient(handler))
var apiUrl = ("http://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&accepted=False&tagged=asp.net&site=stackoverflow");
httpClient.BaseAddress = new Uri(apiUrl);
var response = await httpClient.GetStringAsync(apiUrl);
Today I learnt how to decompress compressed API responses. Stack Overflow is the only API I’ve come across that compresses its responses, but I’m sure there are others so this will be useful in the future.