Skip to main content

Python

Python

Use requests for sync or aiohttp for async. You can also install the official Python SDK: pip install xcrop

Installation

BASH
pip install requests
# async: pip install aiohttp

Helper Function

xcrop.pyPYTHON
import os, requests

API_KEY = os.environ["XCROP_API_KEY"]
BASE = "https://xcrop.io/api"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

def xcrop_get(path, params=None):
    r = requests.get(BASE + path, headers=HEADERS, params=params)
    r.raise_for_status()
    return r.json()

def xcrop_post(path, body):
    r = requests.post(BASE + path, headers={**HEADERS, "Content-Type": "application/json"}, json=body)
    r.raise_for_status()
    return r.json()

Search Tweets

PYTHON
result = xcrop_post("/v2/search", {
    "query": "#bitcoin",
    "limit": 20,
    "sort": "latest",
})

for tweet in result["data"]:
    print(f"@{tweet['author']['username']}: {tweet['text'][:80]}")
    print(f"  Likes: {tweet['metrics']['likes']} | RT: {tweet['metrics']['retweets']}")

User Profile + Followers

PYTHON
# Get user profile
user = xcrop_get("/v2/users/elonmusk")["data"]
print(f"{user['name']} — {user['followers']} followers")

# Get followers
followers = xcrop_get("/v2/users/elonmusk/followers", {"count": 20})
for f in followers["data"]:
    print(f"  @{f['username']} ({f['followers']} followers)")

Async with aiohttp

PYTHON
import asyncio, aiohttp

async def main():
    async with aiohttp.ClientSession(headers=HEADERS) as s:
        # Parallel requests
        async with s.get(BASE + "/v2/users/elonmusk") as r1, \
                   s.get(BASE + "/v2/trending?country=Japan") as r2:
            user = (await r1.json())["data"]
            trends = (await r2.json())["data"]
            print(f"User: {user['name']}")
            for t in trends[:5]:
                print(f"  #{t['rank']} {t['name']}")

asyncio.run(main())

More in Code Examples

Full documentation with search: xcrop.io/docs