Hey there, fellow developer! Ready to supercharge your SEO toolset? Let's dive into the world of Ahrefs API integration using Python. With the python-ahrefs package, you'll be pulling valuable SEO data like a pro in no time.
Before we jump in, make sure you've got:
First things first, let's get that python-ahrefs package installed:
pip install python-ahrefs
Easy peasy, right?
Now, let's set up that API token. It's as simple as:
from ahrefs import AhrefsApi api = AhrefsApi(token="YOUR_API_TOKEN")
Time to make your first API call. Here's a quick example:
result = api.backlinks("ahrefs.com", "refdomains") print(result)
Boom! You've just pulled some backlink data.
Let's explore some popular endpoints:
backlinks = api.backlinks("example.com", "refdomains")
organic = api.organic_keywords("example.com", "us")
content = api.content_explorer("python programming")
Ahrefs API returns JSON. Parse it like this:
import json data = json.loads(result)
Don't forget to handle those pesky errors:
try: result = api.backlinks("example.com", "refdomains") except Exception as e: print(f"Oops! Something went wrong: {e}")
Ahrefs has rate limits, so play nice! Here's a simple way to respect them:
import time def rate_limited_call(func, *args, **kwargs): result = func(*args, **kwargs) time.sleep(1) # Wait 1 second between calls return result result = rate_limited_call(api.backlinks, "example.com", "refdomains")
Ready to level up? Let's look at batch requests:
domains = ["example1.com", "example2.com", "example3.com"] results = [api.backlinks(domain, "refdomains") for domain in domains]
For async requests, check out the asyncio
library with aiohttp
.
Pandas is your friend for data manipulation:
import pandas as pd df = pd.DataFrame(data['refdomains'])
Want to store results? SQLite is a quick and easy option:
import sqlite3 conn = sqlite3.connect('ahrefs_data.db') df.to_sql('refdomains', conn, if_exists='replace')
Let's put it all together:
from ahrefs import AhrefsApi import pandas as pd api = AhrefsApi(token="YOUR_API_TOKEN") def analyze_domain(domain): backlinks = api.backlinks(domain, "refdomains") organic = api.organic_keywords(domain, "us") df_backlinks = pd.DataFrame(backlinks['refdomains']) df_organic = pd.DataFrame(organic['organic_keywords']) print(f"Domain: {domain}") print(f"Total referring domains: {df_backlinks['refdomain'].nunique()}") print(f"Total organic keywords: {len(df_organic)}") print(f"Top 5 organic keywords by traffic:") print(df_organic.sort_values('traffic', ascending=False).head()) analyze_domain("ahrefs.com")
And there you have it! You're now equipped to build powerful SEO tools with the Ahrefs API and Python. Remember, the sky's the limit here. Keep exploring, keep coding, and most importantly, have fun with it!
For more details, check out the python-ahrefs documentation and the Ahrefs API documentation.
Now go forth and conquer the SEO world with your new Python powers!