sociallens 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sociallens-0.1.0/LICENSE +21 -0
- sociallens-0.1.0/PKG-INFO +175 -0
- sociallens-0.1.0/README.md +151 -0
- sociallens-0.1.0/pyproject.toml +38 -0
- sociallens-0.1.0/setup.cfg +4 -0
- sociallens-0.1.0/src/sociallens/__init__.py +36 -0
- sociallens-0.1.0/src/sociallens/_version.py +1 -0
- sociallens-0.1.0/src/sociallens/client.py +261 -0
- sociallens-0.1.0/src/sociallens/errors.py +95 -0
- sociallens-0.1.0/src/sociallens/py.typed +0 -0
- sociallens-0.1.0/src/sociallens.egg-info/PKG-INFO +175 -0
- sociallens-0.1.0/src/sociallens.egg-info/SOURCES.txt +14 -0
- sociallens-0.1.0/src/sociallens.egg-info/dependency_links.txt +1 -0
- sociallens-0.1.0/src/sociallens.egg-info/requires.txt +1 -0
- sociallens-0.1.0/src/sociallens.egg-info/top_level.txt +1 -0
- sociallens-0.1.0/tests/test_client.py +171 -0
sociallens-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SocialLens
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sociallens
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the SocialLens API: public social media profile, post and comment data from 9 networks as JSON.
|
|
5
|
+
Author: SocialLens
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://sociallens.dev
|
|
8
|
+
Project-URL: Documentation, https://sociallens.dev/docs
|
|
9
|
+
Project-URL: Pricing, https://sociallens.dev/pricing
|
|
10
|
+
Project-URL: Repository, https://github.com/sociallensapi/sociallens-python
|
|
11
|
+
Keywords: sociallens,social media api,follower count,instagram,tiktok,youtube,x,reddit,linkedin,threads,pinterest,facebook
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: requests>=2.25
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# SocialLens Python SDK
|
|
26
|
+
|
|
27
|
+
Official Python client for the [SocialLens API](https://sociallens.dev/docs). It reads public profile, post and comment data from 9 social networks (Instagram, TikTok, YouTube, X, Facebook, LinkedIn, Threads, Pinterest and Reddit) and returns the API's JSON as plain dictionaries.
|
|
28
|
+
|
|
29
|
+
- One request format for every network.
|
|
30
|
+
- Public data only. No login to any social account.
|
|
31
|
+
- Pay as you go: 1 credit per delivered read, and errors are never charged. A new account starts with 250 free reads, no card.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install sociallens
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Python 3.8 or newer. The only dependency is `requests`.
|
|
40
|
+
|
|
41
|
+
## Quickstart
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from sociallens import SocialLens
|
|
45
|
+
|
|
46
|
+
client = SocialLens("YOUR_API_KEY") # or set SOCIALLENS_API_KEY and call SocialLens()
|
|
47
|
+
|
|
48
|
+
profile = client.profile("instagram", "nasa")
|
|
49
|
+
print(profile["followers"], profile["is_exact"])
|
|
50
|
+
|
|
51
|
+
post = client.post("tiktok", "https://www.tiktok.com/@tiktok/video/7106594312292453675")
|
|
52
|
+
print(post["likes"], post["views"], post["comments"])
|
|
53
|
+
|
|
54
|
+
page = client.profile_posts("youtube", "mkbhd", limit=5)
|
|
55
|
+
for item in page["posts"]:
|
|
56
|
+
print(item["published_at"], item["likes"], item["views"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Get a free key at https://sociallens.dev/register.
|
|
60
|
+
|
|
61
|
+
## Methods
|
|
62
|
+
|
|
63
|
+
| Method | Endpoint | Networks |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `ping()` | `GET /v1/ping` | Checks the key. Free |
|
|
66
|
+
| `profile(platform, username)` | `GET /v1/profile` | All 9 |
|
|
67
|
+
| `post(platform, url)` | `GET /v1/post` | All except LinkedIn |
|
|
68
|
+
| `profile_posts(platform, username, limit=10)` | `GET /v1/profile-posts` | All 9 |
|
|
69
|
+
| `post_comments(platform, url, limit=20)` | `GET /v1/post-comments` | TikTok, Instagram, YouTube, Facebook, Reddit |
|
|
70
|
+
| `followers(username, cursor=None)` | `GET /v1/followers` | TikTok |
|
|
71
|
+
| `following(username, cursor=None)` | `GET /v1/following` | TikTok |
|
|
72
|
+
|
|
73
|
+
`platform` is one of `tiktok`, `instagram`, `youtube`, `facebook`, `x`, `reddit`, `linkedin`, `threads`, `pinterest`. The same list is exported as `sociallens.PLATFORMS`, and `sociallens.COVERAGE` maps each method to the networks it supports.
|
|
74
|
+
|
|
75
|
+
Optional keyword arguments on the read methods:
|
|
76
|
+
|
|
77
|
+
- `fresh=True` skips the short read cache.
|
|
78
|
+
- `cache_max_age="1d"` (or `3d`, `7d`, `14d`, `30d`) lets the source answer from its own stored copy.
|
|
79
|
+
- `type="person"` on `profile` reads a LinkedIn person when the username is a name. The default is a company. A full LinkedIn URL needs no `type`.
|
|
80
|
+
|
|
81
|
+
`username` is the public handle, with or without the `@`. On Reddit it is the subreddit name. Facebook and LinkedIn also accept the full URL.
|
|
82
|
+
|
|
83
|
+
## Reading the result
|
|
84
|
+
|
|
85
|
+
Every method returns the JSON body as a `dict`, unchanged. The field reference is in the [API documentation](https://sociallens.dev/docs).
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
profile = client.profile("tiktok", "some_handle")
|
|
89
|
+
|
|
90
|
+
if not profile["exists"]:
|
|
91
|
+
print("No such profile") # a delivered answer, not an error
|
|
92
|
+
elif profile.get("private"):
|
|
93
|
+
print("Private profile")
|
|
94
|
+
else:
|
|
95
|
+
print(profile["followers"]) # exact when profile["is_exact"] is True
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `exists: false` is a result, not an exception.
|
|
99
|
+
- `is_exact` is `False` when the network only publishes a rounded number, for example YouTube subscribers.
|
|
100
|
+
- A counter the network does not publish is `None`, never `0`.
|
|
101
|
+
- `fetched_at` is the time of the read, in UTC.
|
|
102
|
+
- `credits` shows what the call charged and the balance left.
|
|
103
|
+
|
|
104
|
+
Two networks answer `profile` with a different shape. `client.profile("reddit", "science")` returns a subreddit with `active_users` (weekly) and `weekly_contributions`, because Reddit has no follower count. `client.profile("linkedin", "shopify")` returns a company with `followers` and `employee_count`.
|
|
105
|
+
|
|
106
|
+
## Errors
|
|
107
|
+
|
|
108
|
+
An error status raises an exception. No error status is ever charged.
|
|
109
|
+
|
|
110
|
+
| Exception | Status and code |
|
|
111
|
+
| --- | --- |
|
|
112
|
+
| `BadRequestError` | 400 `bad_request` |
|
|
113
|
+
| `AuthenticationError` | 401 `invalid_token` |
|
|
114
|
+
| `InsufficientCreditsError` | 402 `no_credits`, `free_tier_exhausted` |
|
|
115
|
+
| `PermissionDeniedError` | 403 `email_not_verified` |
|
|
116
|
+
| `AccountBusyError` | 409 `account_busy` |
|
|
117
|
+
| `RateLimitError` | 429 `rate_limited` |
|
|
118
|
+
| `NotAvailableError` | 501 `platform_not_available` |
|
|
119
|
+
| `SourceUnavailableError` | 503 `source_unavailable` |
|
|
120
|
+
| `APIConnectionError` | No HTTP answer: network error or timeout |
|
|
121
|
+
|
|
122
|
+
All HTTP errors inherit from `APIError` and carry `status`, `code`, `message`, `body` and `retry_after`. Everything inherits from `SocialLensError`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from sociallens import APIError, RateLimitError, SocialLens
|
|
126
|
+
|
|
127
|
+
client = SocialLens("YOUR_API_KEY")
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
data = client.profile("tiktok", "nasa")
|
|
131
|
+
except RateLimitError as error:
|
|
132
|
+
print("Retry in", error.retry_after, "seconds")
|
|
133
|
+
except APIError as error:
|
|
134
|
+
print(error.status, error.code, error.message)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Retries, timeouts and pace
|
|
138
|
+
|
|
139
|
+
- `409`, `429` and `503` are retried up to `max_retries` times (default 2), waiting the `Retry-After` the API sends. Those statuses are never charged.
|
|
140
|
+
- Network errors and timeouts raise `APIConnectionError` and are not retried, because the read may have completed on the server.
|
|
141
|
+
- The API processes the requests of one account one at a time and allows 60 requests per minute per key. Run reads in sequence: a parallel pool does not finish sooner.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
client = SocialLens("YOUR_API_KEY", timeout=90, max_retries=3)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Paging a TikTok follower list
|
|
148
|
+
|
|
149
|
+
Each page is one credit, so set your own ceiling.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
cursor, pages = None, 0
|
|
153
|
+
while pages < 3:
|
|
154
|
+
page = client.followers("nasa", cursor=cursor)
|
|
155
|
+
for user in page["users"]:
|
|
156
|
+
print(user["username"], user["followers"])
|
|
157
|
+
pages += 1
|
|
158
|
+
if not page["has_more"]:
|
|
159
|
+
break
|
|
160
|
+
cursor = page["next_cursor"]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Billing
|
|
164
|
+
|
|
165
|
+
A delivered answer (HTTP 200) costs 1 credit, and every error costs nothing. For profiles, "does not exist" and "private" are delivered answers. The rules for posts that are not found differ by network and are listed in the [documentation](https://sociallens.dev/docs).
|
|
166
|
+
|
|
167
|
+
## Links
|
|
168
|
+
|
|
169
|
+
- API documentation: https://sociallens.dev/docs
|
|
170
|
+
- Pricing: https://sociallens.dev/pricing
|
|
171
|
+
- Guides: https://sociallens.dev/blog
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# SocialLens Python SDK
|
|
2
|
+
|
|
3
|
+
Official Python client for the [SocialLens API](https://sociallens.dev/docs). It reads public profile, post and comment data from 9 social networks (Instagram, TikTok, YouTube, X, Facebook, LinkedIn, Threads, Pinterest and Reddit) and returns the API's JSON as plain dictionaries.
|
|
4
|
+
|
|
5
|
+
- One request format for every network.
|
|
6
|
+
- Public data only. No login to any social account.
|
|
7
|
+
- Pay as you go: 1 credit per delivered read, and errors are never charged. A new account starts with 250 free reads, no card.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install sociallens
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Python 3.8 or newer. The only dependency is `requests`.
|
|
16
|
+
|
|
17
|
+
## Quickstart
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from sociallens import SocialLens
|
|
21
|
+
|
|
22
|
+
client = SocialLens("YOUR_API_KEY") # or set SOCIALLENS_API_KEY and call SocialLens()
|
|
23
|
+
|
|
24
|
+
profile = client.profile("instagram", "nasa")
|
|
25
|
+
print(profile["followers"], profile["is_exact"])
|
|
26
|
+
|
|
27
|
+
post = client.post("tiktok", "https://www.tiktok.com/@tiktok/video/7106594312292453675")
|
|
28
|
+
print(post["likes"], post["views"], post["comments"])
|
|
29
|
+
|
|
30
|
+
page = client.profile_posts("youtube", "mkbhd", limit=5)
|
|
31
|
+
for item in page["posts"]:
|
|
32
|
+
print(item["published_at"], item["likes"], item["views"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Get a free key at https://sociallens.dev/register.
|
|
36
|
+
|
|
37
|
+
## Methods
|
|
38
|
+
|
|
39
|
+
| Method | Endpoint | Networks |
|
|
40
|
+
| --- | --- | --- |
|
|
41
|
+
| `ping()` | `GET /v1/ping` | Checks the key. Free |
|
|
42
|
+
| `profile(platform, username)` | `GET /v1/profile` | All 9 |
|
|
43
|
+
| `post(platform, url)` | `GET /v1/post` | All except LinkedIn |
|
|
44
|
+
| `profile_posts(platform, username, limit=10)` | `GET /v1/profile-posts` | All 9 |
|
|
45
|
+
| `post_comments(platform, url, limit=20)` | `GET /v1/post-comments` | TikTok, Instagram, YouTube, Facebook, Reddit |
|
|
46
|
+
| `followers(username, cursor=None)` | `GET /v1/followers` | TikTok |
|
|
47
|
+
| `following(username, cursor=None)` | `GET /v1/following` | TikTok |
|
|
48
|
+
|
|
49
|
+
`platform` is one of `tiktok`, `instagram`, `youtube`, `facebook`, `x`, `reddit`, `linkedin`, `threads`, `pinterest`. The same list is exported as `sociallens.PLATFORMS`, and `sociallens.COVERAGE` maps each method to the networks it supports.
|
|
50
|
+
|
|
51
|
+
Optional keyword arguments on the read methods:
|
|
52
|
+
|
|
53
|
+
- `fresh=True` skips the short read cache.
|
|
54
|
+
- `cache_max_age="1d"` (or `3d`, `7d`, `14d`, `30d`) lets the source answer from its own stored copy.
|
|
55
|
+
- `type="person"` on `profile` reads a LinkedIn person when the username is a name. The default is a company. A full LinkedIn URL needs no `type`.
|
|
56
|
+
|
|
57
|
+
`username` is the public handle, with or without the `@`. On Reddit it is the subreddit name. Facebook and LinkedIn also accept the full URL.
|
|
58
|
+
|
|
59
|
+
## Reading the result
|
|
60
|
+
|
|
61
|
+
Every method returns the JSON body as a `dict`, unchanged. The field reference is in the [API documentation](https://sociallens.dev/docs).
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
profile = client.profile("tiktok", "some_handle")
|
|
65
|
+
|
|
66
|
+
if not profile["exists"]:
|
|
67
|
+
print("No such profile") # a delivered answer, not an error
|
|
68
|
+
elif profile.get("private"):
|
|
69
|
+
print("Private profile")
|
|
70
|
+
else:
|
|
71
|
+
print(profile["followers"]) # exact when profile["is_exact"] is True
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- `exists: false` is a result, not an exception.
|
|
75
|
+
- `is_exact` is `False` when the network only publishes a rounded number, for example YouTube subscribers.
|
|
76
|
+
- A counter the network does not publish is `None`, never `0`.
|
|
77
|
+
- `fetched_at` is the time of the read, in UTC.
|
|
78
|
+
- `credits` shows what the call charged and the balance left.
|
|
79
|
+
|
|
80
|
+
Two networks answer `profile` with a different shape. `client.profile("reddit", "science")` returns a subreddit with `active_users` (weekly) and `weekly_contributions`, because Reddit has no follower count. `client.profile("linkedin", "shopify")` returns a company with `followers` and `employee_count`.
|
|
81
|
+
|
|
82
|
+
## Errors
|
|
83
|
+
|
|
84
|
+
An error status raises an exception. No error status is ever charged.
|
|
85
|
+
|
|
86
|
+
| Exception | Status and code |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| `BadRequestError` | 400 `bad_request` |
|
|
89
|
+
| `AuthenticationError` | 401 `invalid_token` |
|
|
90
|
+
| `InsufficientCreditsError` | 402 `no_credits`, `free_tier_exhausted` |
|
|
91
|
+
| `PermissionDeniedError` | 403 `email_not_verified` |
|
|
92
|
+
| `AccountBusyError` | 409 `account_busy` |
|
|
93
|
+
| `RateLimitError` | 429 `rate_limited` |
|
|
94
|
+
| `NotAvailableError` | 501 `platform_not_available` |
|
|
95
|
+
| `SourceUnavailableError` | 503 `source_unavailable` |
|
|
96
|
+
| `APIConnectionError` | No HTTP answer: network error or timeout |
|
|
97
|
+
|
|
98
|
+
All HTTP errors inherit from `APIError` and carry `status`, `code`, `message`, `body` and `retry_after`. Everything inherits from `SocialLensError`.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from sociallens import APIError, RateLimitError, SocialLens
|
|
102
|
+
|
|
103
|
+
client = SocialLens("YOUR_API_KEY")
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
data = client.profile("tiktok", "nasa")
|
|
107
|
+
except RateLimitError as error:
|
|
108
|
+
print("Retry in", error.retry_after, "seconds")
|
|
109
|
+
except APIError as error:
|
|
110
|
+
print(error.status, error.code, error.message)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Retries, timeouts and pace
|
|
114
|
+
|
|
115
|
+
- `409`, `429` and `503` are retried up to `max_retries` times (default 2), waiting the `Retry-After` the API sends. Those statuses are never charged.
|
|
116
|
+
- Network errors and timeouts raise `APIConnectionError` and are not retried, because the read may have completed on the server.
|
|
117
|
+
- The API processes the requests of one account one at a time and allows 60 requests per minute per key. Run reads in sequence: a parallel pool does not finish sooner.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
client = SocialLens("YOUR_API_KEY", timeout=90, max_retries=3)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Paging a TikTok follower list
|
|
124
|
+
|
|
125
|
+
Each page is one credit, so set your own ceiling.
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
cursor, pages = None, 0
|
|
129
|
+
while pages < 3:
|
|
130
|
+
page = client.followers("nasa", cursor=cursor)
|
|
131
|
+
for user in page["users"]:
|
|
132
|
+
print(user["username"], user["followers"])
|
|
133
|
+
pages += 1
|
|
134
|
+
if not page["has_more"]:
|
|
135
|
+
break
|
|
136
|
+
cursor = page["next_cursor"]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Billing
|
|
140
|
+
|
|
141
|
+
A delivered answer (HTTP 200) costs 1 credit, and every error costs nothing. For profiles, "does not exist" and "private" are delivered answers. The rules for posts that are not found differ by network and are listed in the [documentation](https://sociallens.dev/docs).
|
|
142
|
+
|
|
143
|
+
## Links
|
|
144
|
+
|
|
145
|
+
- API documentation: https://sociallens.dev/docs
|
|
146
|
+
- Pricing: https://sociallens.dev/pricing
|
|
147
|
+
- Guides: https://sociallens.dev/blog
|
|
148
|
+
|
|
149
|
+
## License
|
|
150
|
+
|
|
151
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sociallens"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official Python client for the SocialLens API: public social media profile, post and comment data from 9 networks as JSON."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "SocialLens" }]
|
|
13
|
+
keywords = ["sociallens", "social media api", "follower count", "instagram", "tiktok", "youtube", "x", "reddit", "linkedin", "threads", "pinterest", "facebook"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["requests>=2.25"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://sociallens.dev"
|
|
27
|
+
Documentation = "https://sociallens.dev/docs"
|
|
28
|
+
Pricing = "https://sociallens.dev/pricing"
|
|
29
|
+
Repository = "https://github.com/sociallensapi/sociallens-python"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.dynamic]
|
|
32
|
+
version = { attr = "sociallens._version.__version__" }
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.package-data]
|
|
38
|
+
sociallens = ["py.typed"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Official Python client for the SocialLens API (https://sociallens.dev)."""
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .client import CACHE_MAX_AGE, COVERAGE, DEFAULT_BASE_URL, PLATFORMS, SocialLens
|
|
4
|
+
from .errors import (
|
|
5
|
+
AccountBusyError,
|
|
6
|
+
APIConnectionError,
|
|
7
|
+
APIError,
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
BadRequestError,
|
|
10
|
+
InsufficientCreditsError,
|
|
11
|
+
NotAvailableError,
|
|
12
|
+
PermissionDeniedError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
SocialLensError,
|
|
15
|
+
SourceUnavailableError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"__version__",
|
|
20
|
+
"SocialLens",
|
|
21
|
+
"PLATFORMS",
|
|
22
|
+
"COVERAGE",
|
|
23
|
+
"CACHE_MAX_AGE",
|
|
24
|
+
"DEFAULT_BASE_URL",
|
|
25
|
+
"SocialLensError",
|
|
26
|
+
"APIConnectionError",
|
|
27
|
+
"APIError",
|
|
28
|
+
"BadRequestError",
|
|
29
|
+
"AuthenticationError",
|
|
30
|
+
"InsufficientCreditsError",
|
|
31
|
+
"PermissionDeniedError",
|
|
32
|
+
"AccountBusyError",
|
|
33
|
+
"RateLimitError",
|
|
34
|
+
"NotAvailableError",
|
|
35
|
+
"SourceUnavailableError",
|
|
36
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Client for the SocialLens API. Reference: https://sociallens.dev/docs"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .errors import RETRYABLE_STATUSES, STATUS_TO_ERROR, APIConnectionError, APIError
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.sociallens.dev"
|
|
14
|
+
|
|
15
|
+
#: Values accepted by the ``platform`` parameter.
|
|
16
|
+
PLATFORMS = ("tiktok", "instagram", "youtube", "facebook", "x", "reddit", "linkedin", "threads", "pinterest")
|
|
17
|
+
|
|
18
|
+
#: Which platforms each method supports. For reference: the client does not block a call,
|
|
19
|
+
#: the API answers 501 platform_not_available (never charged) when a platform is not offered.
|
|
20
|
+
COVERAGE = {
|
|
21
|
+
"profile": PLATFORMS,
|
|
22
|
+
"post": ("tiktok", "instagram", "youtube", "facebook", "x", "reddit", "threads", "pinterest"),
|
|
23
|
+
"profile_posts": PLATFORMS,
|
|
24
|
+
"post_comments": ("tiktok", "instagram", "youtube", "facebook", "reddit"),
|
|
25
|
+
"followers": ("tiktok",),
|
|
26
|
+
"following": ("tiktok",),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
#: Values accepted by ``cache_max_age``.
|
|
30
|
+
CACHE_MAX_AGE = ("1d", "3d", "7d", "14d", "30d")
|
|
31
|
+
|
|
32
|
+
_DEFAULT_RETRY_DELAY = {409: 2.0, 429: 5.0, 503: 30.0}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SocialLens:
|
|
36
|
+
"""Reads public social media data through the SocialLens API.
|
|
37
|
+
|
|
38
|
+
Every method returns the JSON body of the API as a ``dict``, unchanged.
|
|
39
|
+
A 200 answer is not always a profile with data: check ``exists`` (and ``private``
|
|
40
|
+
on profiles) before reading counters.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
api_key: your key (``sk_live_...``). When omitted, the ``SOCIALLENS_API_KEY``
|
|
44
|
+
environment variable is used.
|
|
45
|
+
base_url: API origin. Change it only for testing.
|
|
46
|
+
timeout: seconds to wait for one HTTP answer.
|
|
47
|
+
max_retries: how many times to retry a 409, 429 or 503. Those statuses are
|
|
48
|
+
never charged. Network errors and timeouts are not retried.
|
|
49
|
+
max_retry_delay: upper bound, in seconds, for one wait between retries.
|
|
50
|
+
session: a ``requests.Session`` to reuse, for example to set proxies.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
api_key: Optional[str] = None,
|
|
56
|
+
*,
|
|
57
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
58
|
+
timeout: float = 60.0,
|
|
59
|
+
max_retries: int = 2,
|
|
60
|
+
max_retry_delay: float = 60.0,
|
|
61
|
+
session: Optional[requests.Session] = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
api_key = api_key or os.environ.get("SOCIALLENS_API_KEY") or os.environ.get("SOCIALLENS_KEY")
|
|
64
|
+
if not api_key:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"No API key. Pass api_key or set SOCIALLENS_API_KEY. "
|
|
67
|
+
"Get a free key at https://sociallens.dev/register"
|
|
68
|
+
)
|
|
69
|
+
self.base_url = base_url.rstrip("/")
|
|
70
|
+
self.timeout = timeout
|
|
71
|
+
self.max_retries = max(0, int(max_retries))
|
|
72
|
+
self.max_retry_delay = max_retry_delay
|
|
73
|
+
self._session = session or requests.Session()
|
|
74
|
+
self._headers = {
|
|
75
|
+
"Authorization": f"Bearer {api_key}",
|
|
76
|
+
"Accept": "application/json",
|
|
77
|
+
"User-Agent": f"sociallens-python/{__version__}",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def __repr__(self) -> str:
|
|
81
|
+
return f"SocialLens(base_url={self.base_url!r})"
|
|
82
|
+
|
|
83
|
+
# ------------------------------------------------------------------ endpoints
|
|
84
|
+
|
|
85
|
+
def ping(self) -> Dict[str, Any]:
|
|
86
|
+
"""GET /v1/ping. Checks the key. Free. Returns ``{"ok": True, "user_id": ...}``."""
|
|
87
|
+
return self._request("ping", {})
|
|
88
|
+
|
|
89
|
+
def profile(
|
|
90
|
+
self,
|
|
91
|
+
platform: str,
|
|
92
|
+
username: str,
|
|
93
|
+
*,
|
|
94
|
+
type: Optional[str] = None,
|
|
95
|
+
fresh: bool = False,
|
|
96
|
+
cache_max_age: Optional[str] = None,
|
|
97
|
+
) -> Dict[str, Any]:
|
|
98
|
+
"""GET /v1/profile. One public profile. All 9 platforms.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
platform: one of ``PLATFORMS``.
|
|
102
|
+
username: the public handle, with or without ``@``. A subreddit name on Reddit.
|
|
103
|
+
A full URL is accepted for Facebook and LinkedIn.
|
|
104
|
+
type: LinkedIn only: ``"company"`` (default) or ``"person"`` when ``username``
|
|
105
|
+
is a name and not a URL.
|
|
106
|
+
fresh: skip the short read cache.
|
|
107
|
+
cache_max_age: ``"1d"``, ``"3d"``, ``"7d"``, ``"14d"`` or ``"30d"``. Lets the
|
|
108
|
+
source answer from its own stored copy.
|
|
109
|
+
"""
|
|
110
|
+
return self._request("profile", {
|
|
111
|
+
"platform": platform,
|
|
112
|
+
"username": username,
|
|
113
|
+
"type": type,
|
|
114
|
+
"fresh": 1 if fresh else None,
|
|
115
|
+
"cache_max_age": cache_max_age,
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
def post(
|
|
119
|
+
self,
|
|
120
|
+
platform: str,
|
|
121
|
+
url: str,
|
|
122
|
+
*,
|
|
123
|
+
fresh: bool = False,
|
|
124
|
+
cache_max_age: Optional[str] = None,
|
|
125
|
+
) -> Dict[str, Any]:
|
|
126
|
+
"""GET /v1/post. One public post or video by URL. All platforms except LinkedIn."""
|
|
127
|
+
return self._request("post", {
|
|
128
|
+
"platform": platform,
|
|
129
|
+
"url": url,
|
|
130
|
+
"fresh": 1 if fresh else None,
|
|
131
|
+
"cache_max_age": cache_max_age,
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
def profile_posts(
|
|
135
|
+
self,
|
|
136
|
+
platform: str,
|
|
137
|
+
username: str,
|
|
138
|
+
*,
|
|
139
|
+
limit: Optional[int] = None,
|
|
140
|
+
fresh: bool = False,
|
|
141
|
+
cache_max_age: Optional[str] = None,
|
|
142
|
+
) -> Dict[str, Any]:
|
|
143
|
+
"""GET /v1/profile-posts. One page of the recent posts of a profile. All 9 platforms.
|
|
144
|
+
|
|
145
|
+
``limit`` goes from 1 to 50 (default 10) and only trims the page.
|
|
146
|
+
"""
|
|
147
|
+
return self._request("profile-posts", {
|
|
148
|
+
"platform": platform,
|
|
149
|
+
"username": username,
|
|
150
|
+
"limit": limit,
|
|
151
|
+
"fresh": 1 if fresh else None,
|
|
152
|
+
"cache_max_age": cache_max_age,
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
def post_comments(
|
|
156
|
+
self,
|
|
157
|
+
platform: str,
|
|
158
|
+
url: str,
|
|
159
|
+
*,
|
|
160
|
+
limit: Optional[int] = None,
|
|
161
|
+
fresh: bool = False,
|
|
162
|
+
cache_max_age: Optional[str] = None,
|
|
163
|
+
) -> Dict[str, Any]:
|
|
164
|
+
"""GET /v1/post-comments. One page of the comments of a post.
|
|
165
|
+
|
|
166
|
+
TikTok, Instagram, YouTube, Facebook and Reddit. ``limit`` goes from 1 to 100
|
|
167
|
+
(default 20) and only trims the page.
|
|
168
|
+
"""
|
|
169
|
+
return self._request("post-comments", {
|
|
170
|
+
"platform": platform,
|
|
171
|
+
"url": url,
|
|
172
|
+
"limit": limit,
|
|
173
|
+
"fresh": 1 if fresh else None,
|
|
174
|
+
"cache_max_age": cache_max_age,
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
def followers(
|
|
178
|
+
self,
|
|
179
|
+
username: str,
|
|
180
|
+
*,
|
|
181
|
+
platform: str = "tiktok",
|
|
182
|
+
cursor: Optional[str] = None,
|
|
183
|
+
cache_max_age: Optional[str] = None,
|
|
184
|
+
) -> Dict[str, Any]:
|
|
185
|
+
"""GET /v1/followers. One page of the follower list. TikTok only.
|
|
186
|
+
|
|
187
|
+
Pass ``next_cursor`` from the previous answer as ``cursor`` to read the next page.
|
|
188
|
+
Each page is one credit.
|
|
189
|
+
"""
|
|
190
|
+
return self._request("followers", {
|
|
191
|
+
"platform": platform,
|
|
192
|
+
"username": username,
|
|
193
|
+
"cursor": cursor,
|
|
194
|
+
"cache_max_age": cache_max_age,
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
def following(
|
|
198
|
+
self,
|
|
199
|
+
username: str,
|
|
200
|
+
*,
|
|
201
|
+
platform: str = "tiktok",
|
|
202
|
+
cursor: Optional[str] = None,
|
|
203
|
+
cache_max_age: Optional[str] = None,
|
|
204
|
+
) -> Dict[str, Any]:
|
|
205
|
+
"""GET /v1/following. One page of the accounts a profile follows. TikTok only."""
|
|
206
|
+
return self._request("following", {
|
|
207
|
+
"platform": platform,
|
|
208
|
+
"username": username,
|
|
209
|
+
"cursor": cursor,
|
|
210
|
+
"cache_max_age": cache_max_age,
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
# ------------------------------------------------------------------ transport
|
|
214
|
+
|
|
215
|
+
def _request(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
216
|
+
query = {key: value for key, value in params.items() if value is not None}
|
|
217
|
+
url = f"{self.base_url}/v1/{path}"
|
|
218
|
+
attempt = 0
|
|
219
|
+
while True:
|
|
220
|
+
try:
|
|
221
|
+
response = self._session.get(url, params=query, headers=self._headers, timeout=self.timeout)
|
|
222
|
+
except requests.RequestException as exc:
|
|
223
|
+
raise APIConnectionError(f"Could not reach {url}: {exc}") from exc
|
|
224
|
+
|
|
225
|
+
body = self._decode(response)
|
|
226
|
+
status = response.status_code
|
|
227
|
+
if status == 200:
|
|
228
|
+
if body is None:
|
|
229
|
+
raise APIError("The API answered 200 with a body that is not JSON.", status=status)
|
|
230
|
+
return body
|
|
231
|
+
|
|
232
|
+
error = self._build_error(response, body or {})
|
|
233
|
+
if status in RETRYABLE_STATUSES and attempt < self.max_retries:
|
|
234
|
+
attempt += 1
|
|
235
|
+
delay = error.retry_after if error.retry_after is not None else _DEFAULT_RETRY_DELAY[status]
|
|
236
|
+
time.sleep(min(delay, self.max_retry_delay))
|
|
237
|
+
continue
|
|
238
|
+
raise error
|
|
239
|
+
|
|
240
|
+
@staticmethod
|
|
241
|
+
def _decode(response: requests.Response) -> Optional[Dict[str, Any]]:
|
|
242
|
+
try:
|
|
243
|
+
body = response.json()
|
|
244
|
+
except ValueError:
|
|
245
|
+
return None
|
|
246
|
+
return body if isinstance(body, dict) else None
|
|
247
|
+
|
|
248
|
+
@staticmethod
|
|
249
|
+
def _build_error(response: requests.Response, body: Dict[str, Any]) -> APIError:
|
|
250
|
+
status = response.status_code
|
|
251
|
+
code = body.get("error") if isinstance(body.get("error"), str) else None
|
|
252
|
+
message = body.get("message") if isinstance(body.get("message"), str) else f"HTTP {status}"
|
|
253
|
+
retry_after: Optional[float] = None
|
|
254
|
+
for raw in (response.headers.get("Retry-After"), body.get("retry_after")):
|
|
255
|
+
try:
|
|
256
|
+
retry_after = float(raw) # type: ignore[arg-type]
|
|
257
|
+
break
|
|
258
|
+
except (TypeError, ValueError):
|
|
259
|
+
continue
|
|
260
|
+
error_class = STATUS_TO_ERROR.get(status, APIError)
|
|
261
|
+
return error_class(message, status=status, code=code, body=body, retry_after=retry_after)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Exceptions raised by the SocialLens client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SocialLensError(Exception):
|
|
8
|
+
"""Base class for every error raised by this package."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class APIConnectionError(SocialLensError):
|
|
12
|
+
"""The request got no HTTP answer: network error or timeout.
|
|
13
|
+
|
|
14
|
+
A read that timed out on your side may still have completed on the server,
|
|
15
|
+
so the client never retries these on its own.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class APIError(SocialLensError):
|
|
20
|
+
"""The API answered with an error status. Error statuses are never charged.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
status: HTTP status code.
|
|
24
|
+
code: the "error" field of the JSON body, for example "rate_limited".
|
|
25
|
+
message: the "message" field of the JSON body.
|
|
26
|
+
body: the decoded JSON body ({} when the body was not JSON).
|
|
27
|
+
retry_after: seconds to wait before a retry, when the API sent it.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
message: str,
|
|
33
|
+
*,
|
|
34
|
+
status: int,
|
|
35
|
+
code: Optional[str] = None,
|
|
36
|
+
body: Optional[Dict[str, Any]] = None,
|
|
37
|
+
retry_after: Optional[float] = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.message = message
|
|
41
|
+
self.status = status
|
|
42
|
+
self.code = code
|
|
43
|
+
self.body = body or {}
|
|
44
|
+
self.retry_after = retry_after
|
|
45
|
+
|
|
46
|
+
def __str__(self) -> str:
|
|
47
|
+
code = f" {self.code}" if self.code else ""
|
|
48
|
+
return f"[{self.status}{code}] {self.message}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BadRequestError(APIError):
|
|
52
|
+
"""400 bad_request: a parameter is missing or invalid."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AuthenticationError(APIError):
|
|
56
|
+
"""401 invalid_token: the API key is missing, wrong or revoked."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InsufficientCreditsError(APIError):
|
|
60
|
+
"""402 no_credits or free_tier_exhausted: no balance left."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PermissionDeniedError(APIError):
|
|
64
|
+
"""403 email_not_verified: confirm your email before using the API."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class AccountBusyError(APIError):
|
|
68
|
+
"""409 account_busy: another request of this account is in progress."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class RateLimitError(APIError):
|
|
72
|
+
"""429 rate_limited: more than 60 requests per minute on one key."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class NotAvailableError(APIError):
|
|
76
|
+
"""501 platform_not_available: the platform is not offered on this endpoint."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class SourceUnavailableError(APIError):
|
|
80
|
+
"""503 source_unavailable: the network could not be read right now."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
STATUS_TO_ERROR = {
|
|
84
|
+
400: BadRequestError,
|
|
85
|
+
401: AuthenticationError,
|
|
86
|
+
402: InsufficientCreditsError,
|
|
87
|
+
403: PermissionDeniedError,
|
|
88
|
+
409: AccountBusyError,
|
|
89
|
+
429: RateLimitError,
|
|
90
|
+
501: NotAvailableError,
|
|
91
|
+
503: SourceUnavailableError,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# Statuses that are safe to retry: the read was not delivered and nothing was charged.
|
|
95
|
+
RETRYABLE_STATUSES = (409, 429, 503)
|
|
File without changes
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sociallens
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the SocialLens API: public social media profile, post and comment data from 9 networks as JSON.
|
|
5
|
+
Author: SocialLens
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://sociallens.dev
|
|
8
|
+
Project-URL: Documentation, https://sociallens.dev/docs
|
|
9
|
+
Project-URL: Pricing, https://sociallens.dev/pricing
|
|
10
|
+
Project-URL: Repository, https://github.com/sociallensapi/sociallens-python
|
|
11
|
+
Keywords: sociallens,social media api,follower count,instagram,tiktok,youtube,x,reddit,linkedin,threads,pinterest,facebook
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: requests>=2.25
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# SocialLens Python SDK
|
|
26
|
+
|
|
27
|
+
Official Python client for the [SocialLens API](https://sociallens.dev/docs). It reads public profile, post and comment data from 9 social networks (Instagram, TikTok, YouTube, X, Facebook, LinkedIn, Threads, Pinterest and Reddit) and returns the API's JSON as plain dictionaries.
|
|
28
|
+
|
|
29
|
+
- One request format for every network.
|
|
30
|
+
- Public data only. No login to any social account.
|
|
31
|
+
- Pay as you go: 1 credit per delivered read, and errors are never charged. A new account starts with 250 free reads, no card.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install sociallens
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Python 3.8 or newer. The only dependency is `requests`.
|
|
40
|
+
|
|
41
|
+
## Quickstart
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from sociallens import SocialLens
|
|
45
|
+
|
|
46
|
+
client = SocialLens("YOUR_API_KEY") # or set SOCIALLENS_API_KEY and call SocialLens()
|
|
47
|
+
|
|
48
|
+
profile = client.profile("instagram", "nasa")
|
|
49
|
+
print(profile["followers"], profile["is_exact"])
|
|
50
|
+
|
|
51
|
+
post = client.post("tiktok", "https://www.tiktok.com/@tiktok/video/7106594312292453675")
|
|
52
|
+
print(post["likes"], post["views"], post["comments"])
|
|
53
|
+
|
|
54
|
+
page = client.profile_posts("youtube", "mkbhd", limit=5)
|
|
55
|
+
for item in page["posts"]:
|
|
56
|
+
print(item["published_at"], item["likes"], item["views"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Get a free key at https://sociallens.dev/register.
|
|
60
|
+
|
|
61
|
+
## Methods
|
|
62
|
+
|
|
63
|
+
| Method | Endpoint | Networks |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `ping()` | `GET /v1/ping` | Checks the key. Free |
|
|
66
|
+
| `profile(platform, username)` | `GET /v1/profile` | All 9 |
|
|
67
|
+
| `post(platform, url)` | `GET /v1/post` | All except LinkedIn |
|
|
68
|
+
| `profile_posts(platform, username, limit=10)` | `GET /v1/profile-posts` | All 9 |
|
|
69
|
+
| `post_comments(platform, url, limit=20)` | `GET /v1/post-comments` | TikTok, Instagram, YouTube, Facebook, Reddit |
|
|
70
|
+
| `followers(username, cursor=None)` | `GET /v1/followers` | TikTok |
|
|
71
|
+
| `following(username, cursor=None)` | `GET /v1/following` | TikTok |
|
|
72
|
+
|
|
73
|
+
`platform` is one of `tiktok`, `instagram`, `youtube`, `facebook`, `x`, `reddit`, `linkedin`, `threads`, `pinterest`. The same list is exported as `sociallens.PLATFORMS`, and `sociallens.COVERAGE` maps each method to the networks it supports.
|
|
74
|
+
|
|
75
|
+
Optional keyword arguments on the read methods:
|
|
76
|
+
|
|
77
|
+
- `fresh=True` skips the short read cache.
|
|
78
|
+
- `cache_max_age="1d"` (or `3d`, `7d`, `14d`, `30d`) lets the source answer from its own stored copy.
|
|
79
|
+
- `type="person"` on `profile` reads a LinkedIn person when the username is a name. The default is a company. A full LinkedIn URL needs no `type`.
|
|
80
|
+
|
|
81
|
+
`username` is the public handle, with or without the `@`. On Reddit it is the subreddit name. Facebook and LinkedIn also accept the full URL.
|
|
82
|
+
|
|
83
|
+
## Reading the result
|
|
84
|
+
|
|
85
|
+
Every method returns the JSON body as a `dict`, unchanged. The field reference is in the [API documentation](https://sociallens.dev/docs).
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
profile = client.profile("tiktok", "some_handle")
|
|
89
|
+
|
|
90
|
+
if not profile["exists"]:
|
|
91
|
+
print("No such profile") # a delivered answer, not an error
|
|
92
|
+
elif profile.get("private"):
|
|
93
|
+
print("Private profile")
|
|
94
|
+
else:
|
|
95
|
+
print(profile["followers"]) # exact when profile["is_exact"] is True
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `exists: false` is a result, not an exception.
|
|
99
|
+
- `is_exact` is `False` when the network only publishes a rounded number, for example YouTube subscribers.
|
|
100
|
+
- A counter the network does not publish is `None`, never `0`.
|
|
101
|
+
- `fetched_at` is the time of the read, in UTC.
|
|
102
|
+
- `credits` shows what the call charged and the balance left.
|
|
103
|
+
|
|
104
|
+
Two networks answer `profile` with a different shape. `client.profile("reddit", "science")` returns a subreddit with `active_users` (weekly) and `weekly_contributions`, because Reddit has no follower count. `client.profile("linkedin", "shopify")` returns a company with `followers` and `employee_count`.
|
|
105
|
+
|
|
106
|
+
## Errors
|
|
107
|
+
|
|
108
|
+
An error status raises an exception. No error status is ever charged.
|
|
109
|
+
|
|
110
|
+
| Exception | Status and code |
|
|
111
|
+
| --- | --- |
|
|
112
|
+
| `BadRequestError` | 400 `bad_request` |
|
|
113
|
+
| `AuthenticationError` | 401 `invalid_token` |
|
|
114
|
+
| `InsufficientCreditsError` | 402 `no_credits`, `free_tier_exhausted` |
|
|
115
|
+
| `PermissionDeniedError` | 403 `email_not_verified` |
|
|
116
|
+
| `AccountBusyError` | 409 `account_busy` |
|
|
117
|
+
| `RateLimitError` | 429 `rate_limited` |
|
|
118
|
+
| `NotAvailableError` | 501 `platform_not_available` |
|
|
119
|
+
| `SourceUnavailableError` | 503 `source_unavailable` |
|
|
120
|
+
| `APIConnectionError` | No HTTP answer: network error or timeout |
|
|
121
|
+
|
|
122
|
+
All HTTP errors inherit from `APIError` and carry `status`, `code`, `message`, `body` and `retry_after`. Everything inherits from `SocialLensError`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from sociallens import APIError, RateLimitError, SocialLens
|
|
126
|
+
|
|
127
|
+
client = SocialLens("YOUR_API_KEY")
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
data = client.profile("tiktok", "nasa")
|
|
131
|
+
except RateLimitError as error:
|
|
132
|
+
print("Retry in", error.retry_after, "seconds")
|
|
133
|
+
except APIError as error:
|
|
134
|
+
print(error.status, error.code, error.message)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Retries, timeouts and pace
|
|
138
|
+
|
|
139
|
+
- `409`, `429` and `503` are retried up to `max_retries` times (default 2), waiting the `Retry-After` the API sends. Those statuses are never charged.
|
|
140
|
+
- Network errors and timeouts raise `APIConnectionError` and are not retried, because the read may have completed on the server.
|
|
141
|
+
- The API processes the requests of one account one at a time and allows 60 requests per minute per key. Run reads in sequence: a parallel pool does not finish sooner.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
client = SocialLens("YOUR_API_KEY", timeout=90, max_retries=3)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Paging a TikTok follower list
|
|
148
|
+
|
|
149
|
+
Each page is one credit, so set your own ceiling.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
cursor, pages = None, 0
|
|
153
|
+
while pages < 3:
|
|
154
|
+
page = client.followers("nasa", cursor=cursor)
|
|
155
|
+
for user in page["users"]:
|
|
156
|
+
print(user["username"], user["followers"])
|
|
157
|
+
pages += 1
|
|
158
|
+
if not page["has_more"]:
|
|
159
|
+
break
|
|
160
|
+
cursor = page["next_cursor"]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Billing
|
|
164
|
+
|
|
165
|
+
A delivered answer (HTTP 200) costs 1 credit, and every error costs nothing. For profiles, "does not exist" and "private" are delivered answers. The rules for posts that are not found differ by network and are listed in the [documentation](https://sociallens.dev/docs).
|
|
166
|
+
|
|
167
|
+
## Links
|
|
168
|
+
|
|
169
|
+
- API documentation: https://sociallens.dev/docs
|
|
170
|
+
- Pricing: https://sociallens.dev/pricing
|
|
171
|
+
- Guides: https://sociallens.dev/blog
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/sociallens/__init__.py
|
|
5
|
+
src/sociallens/_version.py
|
|
6
|
+
src/sociallens/client.py
|
|
7
|
+
src/sociallens/errors.py
|
|
8
|
+
src/sociallens/py.typed
|
|
9
|
+
src/sociallens.egg-info/PKG-INFO
|
|
10
|
+
src/sociallens.egg-info/SOURCES.txt
|
|
11
|
+
src/sociallens.egg-info/dependency_links.txt
|
|
12
|
+
src/sociallens.egg-info/requires.txt
|
|
13
|
+
src/sociallens.egg-info/top_level.txt
|
|
14
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
requests>=2.25
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sociallens
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Offline tests: the HTTP layer is replaced by a fake session, so no key and no credits are used."""
|
|
2
|
+
import os
|
|
3
|
+
import unittest
|
|
4
|
+
from unittest import mock
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from sociallens import (
|
|
9
|
+
AccountBusyError,
|
|
10
|
+
APIConnectionError,
|
|
11
|
+
APIError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
InsufficientCreditsError,
|
|
14
|
+
NotAvailableError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
SocialLens,
|
|
17
|
+
SourceUnavailableError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FakeResponse:
|
|
22
|
+
def __init__(self, status_code, body=None, headers=None, text=None):
|
|
23
|
+
self.status_code = status_code
|
|
24
|
+
self._body = body
|
|
25
|
+
self.headers = headers or {}
|
|
26
|
+
self._text = text
|
|
27
|
+
|
|
28
|
+
def json(self):
|
|
29
|
+
if self._body is None:
|
|
30
|
+
raise ValueError("not json")
|
|
31
|
+
return self._body
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FakeSession:
|
|
35
|
+
def __init__(self, *responses):
|
|
36
|
+
self.responses = list(responses)
|
|
37
|
+
self.calls = []
|
|
38
|
+
|
|
39
|
+
def get(self, url, params=None, headers=None, timeout=None):
|
|
40
|
+
self.calls.append({"url": url, "params": params, "headers": headers, "timeout": timeout})
|
|
41
|
+
item = self.responses.pop(0)
|
|
42
|
+
if isinstance(item, Exception):
|
|
43
|
+
raise item
|
|
44
|
+
return item
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
PROFILE = {
|
|
48
|
+
"exists": True, "username": "nasa", "platform": "instagram", "private": False,
|
|
49
|
+
"followers": 104237805, "followers_rounded": 104237805, "is_exact": True,
|
|
50
|
+
"fetched_at": "2026-11-24T19:35:58Z", "credits": {"source": "paid", "charged": 1, "balance": 7999},
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def client_with(*responses, **kwargs):
|
|
55
|
+
session = FakeSession(*responses)
|
|
56
|
+
return SocialLens("YOUR_API_KEY", session=session, **kwargs), session
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ClientTests(unittest.TestCase):
|
|
60
|
+
def test_profile_sends_the_documented_request(self):
|
|
61
|
+
client, session = client_with(FakeResponse(200, PROFILE))
|
|
62
|
+
data = client.profile("instagram", "nasa")
|
|
63
|
+
self.assertEqual(data["followers"], 104237805)
|
|
64
|
+
call = session.calls[0]
|
|
65
|
+
self.assertEqual(call["url"], "https://api.sociallens.dev/v1/profile")
|
|
66
|
+
self.assertEqual(call["params"], {"platform": "instagram", "username": "nasa"})
|
|
67
|
+
self.assertEqual(call["headers"]["Authorization"], "Bearer YOUR_API_KEY")
|
|
68
|
+
|
|
69
|
+
def test_optional_parameters(self):
|
|
70
|
+
client, session = client_with(FakeResponse(200, PROFILE), FakeResponse(200, {"exists": True}),
|
|
71
|
+
FakeResponse(200, {"exists": True}), FakeResponse(200, {"exists": True}))
|
|
72
|
+
client.profile("linkedin", "shopify", type="company", fresh=True, cache_max_age="1d")
|
|
73
|
+
self.assertEqual(session.calls[0]["params"], {
|
|
74
|
+
"platform": "linkedin", "username": "shopify", "type": "company", "fresh": 1, "cache_max_age": "1d"})
|
|
75
|
+
client.profile_posts("tiktok", "nasa", limit=5)
|
|
76
|
+
self.assertEqual(session.calls[1]["url"], "https://api.sociallens.dev/v1/profile-posts")
|
|
77
|
+
self.assertEqual(session.calls[1]["params"], {"platform": "tiktok", "username": "nasa", "limit": 5})
|
|
78
|
+
client.post_comments("reddit", "https://www.reddit.com/r/science/comments/abc/x/", limit=20)
|
|
79
|
+
self.assertEqual(session.calls[2]["url"], "https://api.sociallens.dev/v1/post-comments")
|
|
80
|
+
client.followers("nasa", cursor="abc")
|
|
81
|
+
self.assertEqual(session.calls[3]["url"], "https://api.sociallens.dev/v1/followers")
|
|
82
|
+
self.assertEqual(session.calls[3]["params"], {"platform": "tiktok", "username": "nasa", "cursor": "abc"})
|
|
83
|
+
|
|
84
|
+
def test_post_following_and_ping_paths(self):
|
|
85
|
+
client, session = client_with(FakeResponse(200, {"exists": True}), FakeResponse(200, {"exists": True}),
|
|
86
|
+
FakeResponse(200, {"ok": True, "user_id": 1}))
|
|
87
|
+
client.post("tiktok", "https://www.tiktok.com/@tiktok/video/7106594312292453675")
|
|
88
|
+
client.following("nasa")
|
|
89
|
+
self.assertTrue(client.ping()["ok"])
|
|
90
|
+
self.assertEqual([c["url"].rsplit("/", 1)[1] for c in session.calls], ["post", "following", "ping"])
|
|
91
|
+
self.assertEqual(session.calls[0]["params"]["url"], "https://www.tiktok.com/@tiktok/video/7106594312292453675")
|
|
92
|
+
|
|
93
|
+
def test_exists_false_is_a_result_not_an_error(self):
|
|
94
|
+
client, _ = client_with(FakeResponse(200, {"exists": False, "username": "nope", "platform": "tiktok"}))
|
|
95
|
+
self.assertFalse(client.profile("tiktok", "nope")["exists"])
|
|
96
|
+
|
|
97
|
+
def test_invalid_key(self):
|
|
98
|
+
client, _ = client_with(FakeResponse(401, {"error": "invalid_token", "message": "API key missing, invalid or revoked."}))
|
|
99
|
+
with self.assertRaises(AuthenticationError) as ctx:
|
|
100
|
+
client.ping()
|
|
101
|
+
self.assertEqual(ctx.exception.status, 401)
|
|
102
|
+
self.assertEqual(ctx.exception.code, "invalid_token")
|
|
103
|
+
|
|
104
|
+
def test_no_credits_and_not_available(self):
|
|
105
|
+
client, _ = client_with(FakeResponse(402, {"error": "no_credits", "message": "No credits left."}),
|
|
106
|
+
FakeResponse(501, {"error": "platform_not_available", "message": "Not available."}))
|
|
107
|
+
with self.assertRaises(InsufficientCreditsError):
|
|
108
|
+
client.profile("tiktok", "nasa")
|
|
109
|
+
with self.assertRaises(NotAvailableError):
|
|
110
|
+
client.followers("nasa", platform="instagram")
|
|
111
|
+
|
|
112
|
+
def test_rate_limit_is_retried_using_retry_after(self):
|
|
113
|
+
client, session = client_with(
|
|
114
|
+
FakeResponse(429, {"error": "rate_limited", "message": "Too many requests.", "retry_after": 7},
|
|
115
|
+
headers={"Retry-After": "7"}),
|
|
116
|
+
FakeResponse(200, PROFILE))
|
|
117
|
+
with mock.patch("sociallens.client.time.sleep") as sleep:
|
|
118
|
+
data = client.profile("instagram", "nasa")
|
|
119
|
+
self.assertTrue(data["exists"])
|
|
120
|
+
self.assertEqual(len(session.calls), 2)
|
|
121
|
+
sleep.assert_called_once_with(7.0)
|
|
122
|
+
|
|
123
|
+
def test_source_unavailable_after_retries(self):
|
|
124
|
+
down = FakeResponse(503, {"error": "source_unavailable", "message": "Source unavailable right now."},
|
|
125
|
+
headers={"Retry-After": "30"})
|
|
126
|
+
client, session = client_with(down, down, down)
|
|
127
|
+
with mock.patch("sociallens.client.time.sleep") as sleep:
|
|
128
|
+
with self.assertRaises(SourceUnavailableError) as ctx:
|
|
129
|
+
client.profile("instagram", "nasa")
|
|
130
|
+
self.assertEqual(len(session.calls), 3)
|
|
131
|
+
self.assertEqual(sleep.call_count, 2)
|
|
132
|
+
self.assertEqual(ctx.exception.retry_after, 30.0)
|
|
133
|
+
|
|
134
|
+
def test_account_busy_without_retries(self):
|
|
135
|
+
client, session = client_with(FakeResponse(409, {"error": "account_busy", "message": "Busy."}), max_retries=0)
|
|
136
|
+
with self.assertRaises(AccountBusyError):
|
|
137
|
+
client.profile("instagram", "nasa")
|
|
138
|
+
self.assertEqual(len(session.calls), 1)
|
|
139
|
+
|
|
140
|
+
def test_rate_limit_error_class(self):
|
|
141
|
+
client, _ = client_with(FakeResponse(429, {"error": "rate_limited", "message": "Too many."}), max_retries=0)
|
|
142
|
+
with self.assertRaises(RateLimitError):
|
|
143
|
+
client.profile("instagram", "nasa")
|
|
144
|
+
|
|
145
|
+
def test_network_error_is_not_retried(self):
|
|
146
|
+
client, session = client_with(requests.ConnectionError("boom"))
|
|
147
|
+
with self.assertRaises(APIConnectionError):
|
|
148
|
+
client.profile("instagram", "nasa")
|
|
149
|
+
self.assertEqual(len(session.calls), 1)
|
|
150
|
+
|
|
151
|
+
def test_non_json_error_body(self):
|
|
152
|
+
client, _ = client_with(FakeResponse(500, None, text="<html>error</html>"))
|
|
153
|
+
with self.assertRaises(APIError) as ctx:
|
|
154
|
+
client.profile("instagram", "nasa")
|
|
155
|
+
self.assertEqual(ctx.exception.status, 500)
|
|
156
|
+
self.assertIsNone(ctx.exception.code)
|
|
157
|
+
|
|
158
|
+
def test_missing_key(self):
|
|
159
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
160
|
+
with self.assertRaises(ValueError):
|
|
161
|
+
SocialLens()
|
|
162
|
+
|
|
163
|
+
def test_key_from_environment(self):
|
|
164
|
+
with mock.patch.dict(os.environ, {"SOCIALLENS_API_KEY": "YOUR_API_KEY"}, clear=True):
|
|
165
|
+
client = SocialLens(session=FakeSession())
|
|
166
|
+
self.assertEqual(client._headers["Authorization"], "Bearer YOUR_API_KEY")
|
|
167
|
+
self.assertNotIn("YOUR_API_KEY", repr(client))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
if __name__ == "__main__":
|
|
171
|
+
unittest.main()
|