Stack Exchange API in Python#
By Sebastian Shirk and Avery Fernandez
The Stack Exchange API provides programmatic access to data from Stack Exchange network sites like Stack Overflow, Server Fault, and Super User, allowing developers to interact with questions, answers, users, and more.
Please see the following resources for more information on API usage:
- Documentation 
- Terms 
- Data Reuse 
NOTE: The Stack Exchange API has specific throttling measures:
- IP-based throttle: Maximum of 30 requests per second per IP address. Exceeding this limit results in temporary banning, typically from 30 seconds to several minutes. 
- Daily quotas: - Applications without an - access_tokenshare an IP-based daily quota, which defaults to 10,000 requests per day.
- Applications with a valid - access_tokenhave a distinct user/app pair quota, also defaulting to 10,000 requests per day.
 
These recipe examples were tested on May 7, 2025.
Setup#
The following external libraries need to be installed into your environment to run the code examples in this tutorial:
We import the libraries used in this tutorial below:
import requests
import datetime
import pandas as pd
from pprint import pprint
2. Get Questions Based on Title#
Change the title variable to get questions based on different titles.
title = 'How to use Python'
endpoint = 'search'
params = {
    'order': 'desc',
    'sort': 'activity',
    'intitle': title,
    'site': 'stackoverflow'
}
try:
    response = requests.get(BASE_URL + endpoint, params=params)
    # Raise an error for bad responses
    response.raise_for_status()  
    data = response.json()
    pprint(data, depth=1)
except requests.exceptions.RequestException as e:
    print(f"Error fetching data: {e}")
    data = None
{'has_more': True, 'items': [...], 'quota_max': 300, 'quota_remaining': 297}
if data:
    # Extract the items from the response
    search_results = data.get('items', [])
    
    for search_result in search_results[:5]:
        search_result_last_activity = convert_unix(search_result.get('last_activity_date'))
        search_result_creation = convert_unix(search_result.get('creation_date'))
        search_result_title = search_result.get('title')
        search_result_link = search_result.get('link')
        print(f"Title: {search_result_title}")
        print(f"Link: {search_result_link}")
        print(f"Last Activity: {search_result_last_activity}")
        print(f"Creation Date: {search_result_creation}")
        print("-" * 80)
Title: How to use Python Unittest TearDownClass with TestResult.wasSuccessful()
Link: https://stackoverflow.com/questions/25630630/how-to-use-python-unittest-teardownclass-with-testresult-wassuccessful
Last Activity: 2025-05-05 02:03:15
Creation Date: 2014-09-02 14:11:33
--------------------------------------------------------------------------------
Title: Can or How to use Python asyncio on Google Cloud Functions?
Link: https://stackoverflow.com/questions/52755996/can-or-how-to-use-python-asyncio-on-google-cloud-functions
Last Activity: 2025-04-16 12:21:10
Creation Date: 2018-10-11 03:51:31
--------------------------------------------------------------------------------
Title: How to use python descriptors with default_factory in dataclass
Link: https://stackoverflow.com/questions/76090498/how-to-use-python-descriptors-with-default-factory-in-dataclass
Last Activity: 2025-04-06 17:01:34
Creation Date: 2023-04-24 04:31:08
--------------------------------------------------------------------------------
Title: How to use Python type hinting to mock values and perform static analysis when a value can exceed a bound at runtime?
Link: https://stackoverflow.com/questions/79542658/how-to-use-python-type-hinting-to-mock-values-and-perform-static-analysis-when-a
Last Activity: 2025-03-28 20:16:44
Creation Date: 2025-03-28 20:16:44
--------------------------------------------------------------------------------
Title: How to use python requests to get Auth values
Link: https://stackoverflow.com/questions/79535050/how-to-use-python-requests-to-get-auth-values
Last Activity: 2025-03-25 19:27:40
Creation Date: 2025-03-25 18:10:11
--------------------------------------------------------------------------------
3. Get Questions Based on Similarity#
Change the title variable to get questions based on different titles.
title = 'How to use Python'
endpoint = 'similar'
params = {
    'order': 'desc',
    'sort': 'activity',
    'title': title,
    'site': 'stackoverflow'
}
try:
    response = requests.get(BASE_URL + endpoint, params=params)
    # Raise an error for bad responses
    response.raise_for_status()  
    data = response.json()
    pprint(data, depth=1)
except requests.exceptions.RequestException as e:
    print(f"Error fetching data: {e}")
    data = None
{'has_more': True, 'items': [...], 'quota_max': 300, 'quota_remaining': 296}
if data:
    # Extract the items from the response
    similar_questions = data.get('items', [])
    for similar_question in similar_questions[:5]:
        last_activity = convert_unix(similar_question.get('last_activity_date'))
        similar_question_creation = convert_unix(similar_question.get('creation_date'))
        similar_question_title = similar_question.get('title')
        similar_question_link = similar_question.get('link')
        print(f"Title: {similar_question_title}")
        print(f"Link: {similar_question_link}")
        print(f"Last Activity: {last_activity}")
        print(f"Creation Date: {similar_question_creation}")
        print("-" * 80)
Title: C how to open/close a file in a function in a endless loop
Link: https://stackoverflow.com/questions/79611253/c-how-to-open-close-a-file-in-a-function-in-a-endless-loop
Last Activity: 2025-05-07 14:21:45
Creation Date: 2025-05-07 13:56:57
--------------------------------------------------------------------------------
Title: Sort array by filenames independent of path
Link: https://stackoverflow.com/questions/79611186/sort-array-by-filenames-independent-of-path
Last Activity: 2025-05-07 14:21:17
Creation Date: 2025-05-07 13:10:34
--------------------------------------------------------------------------------
Title: Common parent of DefaultMutableTreeNode collection
Link: https://stackoverflow.com/questions/79610079/common-parent-of-defaultmutabletreenode-collection
Last Activity: 2025-05-07 14:21:10
Creation Date: 2025-05-07 03:17:37
--------------------------------------------------------------------------------
Title: GoHighLevel Custom Payment Provider — JS in payment.html not executing (iframe issue?)
Link: https://stackoverflow.com/questions/79611279/gohighlevel-custom-payment-provider-js-in-payment-html-not-executing-iframe-i
Last Activity: 2025-05-07 14:21:09
Creation Date: 2025-05-07 14:21:09
--------------------------------------------------------------------------------
Title: What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__()
Link: https://stackoverflow.com/questions/222877/what-does-super-do-in-python-difference-between-super-init-and-expl
Last Activity: 2025-05-07 14:20:19
Creation Date: 2008-10-21 13:13:15
--------------------------------------------------------------------------------
4. Get Answers and Comments to a Question#
Get all answers to a question based on the question ID. Question ID can be found using the above methods.
Comments appear above the answers in the output.
A filter is used on this query. Filters can be found here.
Hit Run to get a json output of all the included fields in the default filter. You can then choose to add fields that aren’t there or exclude fields that you don’t need.
Once you input all of your included and excluded fields, hit Run again and scroll the json all the way to the bottom. You should see "filter": "{string}" where the string is the filter.
Copy and paste this filter into your code to use it.
Here we have already generated a filter for us to use.
# Get all answers to a specific question using a question id
question_id = 33180743
filter = '!22ZfkjBmMx*-LZeN4vanL'
endpoint = f'questions/{question_id}/answers'
params = {
    'order': 'desc',
    'sort': 'activity',
    'site': 'stackoverflow',
    'filter': filter
}
try:
    response = requests.get(BASE_URL + endpoint, params=params)
    # Raise an error for bad responses
    response.raise_for_status()  
    data = response.json()
    pprint(data, depth=1)
except requests.exceptions.RequestException as e:
    print(f"Error fetching data: {e}")
    data = None
{'has_more': False, 'items': [...], 'quota_max': 300, 'quota_remaining': 295}
if data:
    # Extract the items from the response
    answers = data.get('items', [])
    
    for answer in answers[:5]:
        answer_last_activity = convert_unix(answer.get('last_activity_date'))
        answer_creation = convert_unix(answer.get('creation_date'))
        answer_body = answer.get('body')
        answer_link = answer.get('link')
        print(f"Answer Body: {answer_body}")
        print(f"Link: {answer_link}")
        print(f"Last Activity: {answer_last_activity}")
        print(f"Creation Date: {answer_creation}")
        print("-" * 80)
Answer Body: <p>For someone testing on Emulator, try choosing an emulator that supports Google Play, then Sign In on Google Play</p>
Link: None
Last Activity: 2024-08-07 16:07:33
Creation Date: 2024-08-07 16:07:33
--------------------------------------------------------------------------------
Answer Body: <p>I get In-app billing version 3 NOT supported error when the user is not signed into google play.  Ensure a user is logged into google play on the device.</p>
<p>Update 2023:  Note that you might also get the error "Google Play In-app Billing API version is less than 3" when the user is not logged in to the play store.</p>
Link: None
Last Activity: 2023-04-14 10:57:11
Creation Date: 2017-06-18 09:36:25
--------------------------------------------------------------------------------
Answer Body: <p>Try "Clear Data" and then "Force stop" for Google Play app.</p>
Link: None
Last Activity: 2015-11-02 03:27:33
Creation Date: 2015-10-26 13:01:45
--------------------------------------------------------------------------------
