3

I am working on a project and want to get questions from stack overflow using Stack Overflow API. I searched the way how to achieve the same here:

  1. how to get a list of questions from stackoverflow API based on search query?
  2. Getting null as response from Stack Overflow API with PHP
  3. How to use Stack Overflow API in PHP

But I found nothing useful as they are old techniques. They are using old Stack Overflow API versions.

While going through stackapps I read that to achieve this task I have to register my app. I have registered an app on www.stackapps.com. and I got an APP ID and its SECRET KEY.

I visited here https://api.stackexchange.com/docs/authentication to know how to get data from stack API V 2.2. They have given useful links to get data using Stack Overflow API V 2.0 using authentication via OAuth 2.0

It says ask for a request from user and then get "code" etc. I got stuck here. What should be the process in order to move forward using PHP.

My app should do this:

Let input link be : https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow

I get data of this page in any of the two form either HTML or JSON.

Can it be done without OAuth. If not, then please guide.

Community
  • 1
  • 1
sachinmanit
  • 89
  • 10

1 Answers1

3

Assuming that you have registered your application.

Go to Manage your applications from here https://stackapps.com/apps/oauth

Enable Client side flow within App settings.

Now as you want to create Desktop application, following are steps:

  1. First you need to get Access Token by redirecting user to this link: https://stackexchange.com/oauth/dialog?client_id=[YOUR_APP_ID]&scope=private_info&redirect_uri=https://stackexchange.com/oauth/login_success

  2. You (as a user) will approve the request made by the application. Then you will be redirected to another link in which there will be an access_token.

  3. Grab the access token from there and put it in this link :

https://api.stackexchange.com/2.2/questions?order=descsort=activity&site=stackoverflow&key=[YOUR_APP_KEY]&access_token=[YOUR_ACCESS_TOKEN]&filter=withbody

This will be your ready API.

Get content using:

$context = stream_context_create(array('https' => array('header'=>'Connection: close\r\n')));
$json_array = file_get_contents("YOUR_API_URL", false, $context);
$data = json_decode(gzdecode($json_array),true);
print_r($data); // Show your file data

The data you will get is in JSON and is compressed (in GZIP from). So we decompressed it and then decoded JSON.

This should work. It worked for me. :)

Community
  • 1
  • 1
rachitmanit
  • 324
  • 3
  • 12