Skip to content

Commit 05b7c04

Browse files
How many subs?
1 parent b97a6c5 commit 05b7c04

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

0x16-api_advanced/0-subs.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import requests
2+
3+
def number_of_subscribers(subreddit):
4+
"""
5+
Returns the number of subscribers for a given subreddit.
6+
If the subreddit is invalid, returns 0.
7+
"""
8+
url = f"https://oauth.reddit.com/r/{subreddit}/about"
9+
headers = {"User-Agent": "Mozilla/5.0"}
10+
11+
try:
12+
response = requests.get(url, headers=headers, allow_redirects=False)
13+
response.raise_for_status()
14+
data = response.json()
15+
return data["data"]["subscribers"]
16+
except (requests.exceptions.RequestException, ValueError, KeyError):
17+
return 0

0 commit comments

Comments
 (0)