Ahrefs API Manager

Ahrefs python

by OpenClaudia · MIT license · ★ 705 on GitHub

Ahrefs python cover

Manages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand…

---
name: ahrefs-python
description: Manages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.
---

# Ahrefs Python SDK Skill

## Overview

The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK (`ahrefs-python`) provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.

Key capabilities:
- **Site Explorer** - Backlinks, organic keywords, domain rating, traffic, referring domains
- **Keywords Explorer** - Keyword research, volumes, difficulty, related terms
- **Rank Tracker** - SERP monitoring, competitor tracking
- **Site Audit** - Technical SEO issues, page content, page explorer
- **Brand Radar** - AI brand mentions, share of voice, impressions
- **SERP Overview** - Search result analysis

Overview

The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK (ahrefs-python) provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.

Manual install (npx, ZIP)
Claude Codenpx skills add OpenClaudia/openclaudia-skills --skill ahrefs-python -g -a claude-code
Claude Code (degit)npx degit OpenClaudia/openclaudia-skills/skills/ahrefs-research#main ~/.claude/skills/ahrefs-python
Claude.ai / desktopZip the folder and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md7.4 KB
Read SKILL.md here
OpenClaudia/main1 file shown
SKILL.md
Show the full text212 lines

Ahrefs Python SDK Skill

Overview

The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK (ahrefs-python) provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.

Key capabilities:

  • Site Explorer - Backlinks, organic keywords, domain rating, traffic, referring domains
  • Keywords Explorer - Keyword research, volumes, difficulty, related terms
  • Rank Tracker - SERP monitoring, competitor tracking
  • Site Audit - Technical SEO issues, page content, page explorer
  • Brand Radar - AI brand mentions, share of voice, impressions
  • SERP Overview - Search result analysis
  • Batch Analysis - Bulk domain/URL metrics via POST

Installation

pip3 install git+https://github.com/ahrefs/ahrefs-python.git

Requires Python 3.11+. Dependencies: httpx, pydantic.

API Method Discovery

The SDK has 52 methods across 7 API sections. The built-in search tool is the fastest way to find the right method — it returns matching method signatures, parameters, and return types directly, so there's no need to scan through a large reference.

Python (preferred when already in a Python context):

from ahrefs.search import search_api_methods

# Returns formatted text with method signatures, parameters, and return types
print(search_api_methods("domain rating"))

# Filter by API section and limit results
print(search_api_methods("backlinks", section="site-explorer", limit=3))

CLI (preferred when exploring from the terminal):

# Ensure python3 points to the interpreter where ahrefs-python is installed:
#   which python3
#   python3 -c "import ahrefs"
python3 -m ahrefs.api_search "domain rating"
python3 -m ahrefs.api_search "backlinks" --section site-explorer --limit 3
python3 -m ahrefs.api_search "batch" --json
python3 -m ahrefs.api_search --sections  # list all API sections

IMPORTANT RULES

  • ALWAYS use the ahrefs-python SDK. DO NOT make raw httpx/requests calls to the Ahrefs API.
  • ALWAYS pass dates as strings in YYYY-MM-DD format (e.g. "2025-01-15").
  • ALWAYS use select on list endpoints to request only the columns you need. List endpoints return all columns by default, which wastes API units and increases response size.
  • USE context managers (with / async with) for client lifecycle management.
  • NEVER hardcode API keys in source code. Use the AHREFS_API_KEY environment variable or your preferred secrets mechanism.
  • The client handles retries (429, 5xx, connection errors) automatically. DO NOT implement your own retry logic on top of the SDK.

Quick Start

import os
from ahrefs import AhrefsClient

with AhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
    print(data.domain_rating)  # 91.0
    print(data.ahrefs_rank)    # 3

SDK Patterns

Client Setup
import os
import ahrefs

with ahrefs.AhrefsClient(
    api_key=os.environ["AHREFS_API_KEY"],  # or any secrets source
    base_url="...",          # override API base URL (default: https://api.ahrefs.com/v3)
    timeout=30.0,            # request timeout in seconds (default: 60)
    max_retries=3,           # retries on transient errors (default: 2)
) as client:
    ...

Async client:

import os
from ahrefs import AsyncAhrefsClient

async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    data = await client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")

For parallel calls, use asyncio.gather:

import asyncio

async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    dr_ahrefs, dr_moz = await asyncio.gather(
        client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15"),
        client.site_explorer_domain_rating(target="moz.com", date="2025-01-15"),
    )
Calling Methods

Two calling styles -- both are equivalent:

# Keyword arguments (recommended)
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")

# Request objects (full type safety)
from ahrefs.types import SiteExplorerDomainRatingRequest
request = SiteExplorerDomainRatingRequest(target="ahrefs.com", date="2025-01-15")
data = client.site_explorer_domain_rating(request)

Method names follow {api_section}_{endpoint}, e.g. site_explorer_organic_keywords, keywords_explorer_overview.

Responses

Methods return typed Data objects directly.

Scalar endpoints return a single data object (or None):

data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
print(data.domain_rating)

List endpoints return a list of data objects. There is no pagination — set limit to the number of results you need. Use select to request only the columns you need:

items = client.site_explorer_organic_keywords(
    target="ahrefs.com",
    date="2025-01-15",
    select="keyword,volume,best_position",
    order_by="volume:desc",
    limit=10,
)
for item in items:
    print(item.keyword, item.volume, item.best_position)
Error Handling
import ahrefs

try:
    data = client.site_explorer_domain_rating(target="example.com", date="2025-01-15")
except ahrefs.AuthenticationError:    # 401
    ...
except ahrefs.RateLimitError as e:    # 429 -- e.retry_after has the delay
    ...
except ahrefs.NotFoundError:          # 404
    ...
except ahrefs.APIError as e:          # other 4xx/5xx -- e.status_code, e.response_body
    ...
except ahrefs.APIConnectionError:     # network / timeout
    ...

All exceptions inherit from ahrefs.AhrefsError.

Common Parameters

Most list endpoints share these parameters:

Parameter Type Description
target str Domain, URL, or path to analyze
date str Date in YYYY-MM-DD format
date_from / date_to str Date range for history endpoints
country str Two-letter country code (ISO 3166-1 alpha-2)
select str Comma-separated columns to return
where str Filter expression
order_by str Column and direction, e.g. "volume:desc"
limit int Max results to return

Parameters typed as enums in the API reference (CountryEnum, VolumeModeEnum, etc.) accept plain strings — pass country="us" not CountryEnum("us").

The where parameter takes a JSON string. Use json.dumps() to build it:

import json
where = json.dumps({"field": "volume", "is": ["gte", 1000]})
items = client.site_explorer_organic_keywords(
    target="ahrefs.com", date="2025-01-15",
    select="keyword,volume", where=where,
)

For full filter syntax (boolean combinators, operators, nested fields), see references/filter-syntax.md.

API Methods

Use search_api_methods("query") or python3 -m ahrefs.api_search "query" to find methods by keyword. Search covers all 52 methods across 7 API sections and returns complete signatures, parameters, and response fields.

1---
2name: ahrefs-python
3description: Manages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.
4---
5 
6# Ahrefs Python SDK Skill
7 
8## Overview
9 
10The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK (`ahrefs-python`) provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.
11 
12Key capabilities:
13- **Site Explorer** - Backlinks, organic keywords, domain rating, traffic, referring domains
14- **Keywords Explorer** - Keyword research, volumes, difficulty, related terms
15- **Rank Tracker** - SERP monitoring, competitor tracking
16- **Site Audit** - Technical SEO issues, page content, page explorer
17- **Brand Radar** - AI brand mentions, share of voice, impressions
18- **SERP Overview** - Search result analysis
19- **Batch Analysis** - Bulk domain/URL metrics via POST
20 
21## Installation
22 
23```sh
24pip3 install git+https://github.com/ahrefs/ahrefs-python.git
25```
26 
27Requires Python 3.11+. Dependencies: `httpx`, `pydantic`.
28 
29## API Method Discovery
30 
31The SDK has 52 methods across 7 API sections. The built-in search tool is the fastest way to find the right method — it returns matching method signatures, parameters, and return types directly, so there's no need to scan through a large reference.
32 
33**Python** (preferred when already in a Python context):
34 
35```python
36from ahrefs.search import search_api_methods
37 
38# Returns formatted text with method signatures, parameters, and return types
39print(search_api_methods("domain rating"))
40 
41# Filter by API section and limit results
42print(search_api_methods("backlinks", section="site-explorer", limit=3))
43```
44 
45**CLI** (preferred when exploring from the terminal):
46 
47```sh
48# Ensure python3 points to the interpreter where ahrefs-python is installed:
49# which python3
50# python3 -c "import ahrefs"
51python3 -m ahrefs.api_search "domain rating"
52python3 -m ahrefs.api_search "backlinks" --section site-explorer --limit 3
53python3 -m ahrefs.api_search "batch" --json
54python3 -m ahrefs.api_search --sections # list all API sections
55```
56 
57## IMPORTANT RULES
58 
59- ALWAYS use the `ahrefs-python` SDK. DO NOT make raw `httpx`/`requests` calls to the Ahrefs API.
60- ALWAYS pass dates as strings in `YYYY-MM-DD` format (e.g. `"2025-01-15"`).
61- ALWAYS use `select` on list endpoints to request only the columns you need. List endpoints return all columns by default, which wastes API units and increases response size.
62- USE context managers (`with` / `async with`) for client lifecycle management.
63- NEVER hardcode API keys in source code. Use the `AHREFS_API_KEY` environment variable or your preferred secrets mechanism.
64- The client handles retries (429, 5xx, connection errors) automatically. DO NOT implement your own retry logic on top of the SDK.
65 
66## Quick Start
67 
68```python
69import os
70from ahrefs import AhrefsClient
71 
72with AhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
73 data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
74 print(data.domain_rating) # 91.0
75 print(data.ahrefs_rank) # 3
76```
77 
78## SDK Patterns
79 
80### Client Setup
81 
82```python
83import os
84import ahrefs
85 
86with ahrefs.AhrefsClient(
87 api_key=os.environ["AHREFS_API_KEY"], # or any secrets source
88 base_url="...", # override API base URL (default: https://api.ahrefs.com/v3)
89 timeout=30.0, # request timeout in seconds (default: 60)
90 max_retries=3, # retries on transient errors (default: 2)
91) as client:
92 ...
93```
94 
95Async client:
96 
97```python
98import os
99from ahrefs import AsyncAhrefsClient
100 
101async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
102 data = await client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
103```
104 
105For parallel calls, use `asyncio.gather`:
106 
107```python
108import asyncio
109 
110async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
111 dr_ahrefs, dr_moz = await asyncio.gather(
112 client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15"),
113 client.site_explorer_domain_rating(target="moz.com", date="2025-01-15"),
114 )
115```
116 
117### Calling Methods
118 
119Two calling styles -- both are equivalent:
120 
121```python
122# Keyword arguments (recommended)
123data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
124 
125# Request objects (full type safety)
126from ahrefs.types import SiteExplorerDomainRatingRequest
127request = SiteExplorerDomainRatingRequest(target="ahrefs.com", date="2025-01-15")
128data = client.site_explorer_domain_rating(request)
129```
130 
131Method names follow `{api_section}_{endpoint}`, e.g. `site_explorer_organic_keywords`, `keywords_explorer_overview`.
132 
133### Responses
134 
135Methods return typed Data objects directly.
136 
137**Scalar endpoints** return a single data object (or `None`):
138 
139```python
140data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
141print(data.domain_rating)
142```
143 
144**List endpoints** return a list of data objects. There is no pagination — set `limit` to the number of results you need. Use `select` to request only the columns you need:
145 
146```python
147items = client.site_explorer_organic_keywords(
148 target="ahrefs.com",
149 date="2025-01-15",
150 select="keyword,volume,best_position",
151 order_by="volume:desc",
152 limit=10,
153)
154for item in items:
155 print(item.keyword, item.volume, item.best_position)
156```
157 
158### Error Handling
159 
160```python
161import ahrefs
162 
163try:
164 data = client.site_explorer_domain_rating(target="example.com", date="2025-01-15")
165except ahrefs.AuthenticationError: # 401
166 ...
167except ahrefs.RateLimitError as e: # 429 -- e.retry_after has the delay
168 ...
169except ahrefs.NotFoundError: # 404
170 ...
171except ahrefs.APIError as e: # other 4xx/5xx -- e.status_code, e.response_body
172 ...
173except ahrefs.APIConnectionError: # network / timeout
174 ...
175```
176 
177All exceptions inherit from `ahrefs.AhrefsError`.
178 
179### Common Parameters
180 
181Most list endpoints share these parameters:
182 
183| Parameter | Type | Description |
184|-----------|------|-------------|
185| `target` | `str` | Domain, URL, or path to analyze |
186| `date` | `str` | Date in YYYY-MM-DD format |
187| `date_from` / `date_to` | `str` | Date range for history endpoints |
188| `country` | `str` | Two-letter country code (ISO 3166-1 alpha-2) |
189| `select` | `str` | Comma-separated columns to return |
190| `where` | `str` | Filter expression |
191| `order_by` | `str` | Column and direction, e.g. `"volume:desc"` |
192| `limit` | `int` | Max results to return |
193 
194Parameters typed as enums in the API reference (`CountryEnum`, `VolumeModeEnum`, etc.) accept plain strings — pass `country="us"` not `CountryEnum("us")`.
195 
196The `where` parameter takes a JSON string. Use `json.dumps()` to build it:
197 
198```python
199import json
200where = json.dumps({"field": "volume", "is": ["gte", 1000]})
201items = client.site_explorer_organic_keywords(
202 target="ahrefs.com", date="2025-01-15",
203 select="keyword,volume", where=where,
204)
205```
206 
207For full filter syntax (boolean combinators, operators, nested fields), see `references/filter-syntax.md`.
208 
209## API Methods
210 
211Use `search_api_methods("query")` or `python3 -m ahrefs.api_search "query"` to find methods by keyword. Search covers all 52 methods across 7 API sections and returns complete signatures, parameters, and response fields.
212 
View all files on GitHub →

Details

License
MIT
Stars on the repo
★ 705
Checked
Source
OpenClaudia/openclaudia-skills ↗
Creator
OpenClaudia · 78 listings
View creator

Similar skills

See all →
SkillXberg Document Extractorxberg-io/xberg · by xberg-ioExtract text, tables, metadata, and images from 107 document formats (PDF, Office, images, HTML, email, archives, academic) using Xberg. Use when writing code that calls Xberg APIs in Python, Node.js/TypeScript, Rust, or CLI. Covers installation, extraction (sync/async), configuration (OCR, chunking, output format), batch processing, error handling, and plugins.★ 9.4k GitHub starsSkillCode Migration Validatorkucherenko/jscpd · by kucherenkoMove code from one implementation to another function by function, tests first and code second, and check two implementations of one app for parity, with jscpd --compare as the progress measure and a coverage map binding each function to its tests. Use when porting a library or app to another language or framework (Java to Kotlin, JavaScript to Rust, a Python library to TypeScript, an iOS app to Android), when asked what is left to port, or when comparing the Android and iOS versions of an app.★ 6.3k GitHub starsAgentDocx to Markdown Translatordealfluence/adeu · by dealfluenceDocx ↔ LLM translator. Projects .docx office files to Markdown for editing. Projects edits back to OOXML as tracked changes (redlines). Python and Node.js implementations.★ 165 GitHub starsSkillAmazon White-Background Creatorxianyu110/ecommerce-image-skills · by xianyu110Create an Amazon-compliant white-background main image (pure #FFFFFF background, product fills ≥85% of the frame, no text, props or watermark) from a product photo with GPT Image 2.5, then verify it with a Python check script. Use for Amazon/Walmart/eBay main images, 白底图, 白底主图, hero image, listing main photo.★ 92 GitHub starsAgentSendmux SDKSendmux/sendmux-sdk · by SendmuxOfficial monorepo of SDKs, CLI, and MCP servers for Sendmux email APIs across TypeScript, Python, Go, PHP, Rust, and Ruby.★ 65 GitHub starsSkillSource-Driven Developmentaddyosmani/agent-skills · by addyosmaniGrounds every implementation decision in official documentation. Use when you want to verify an approach against the official docs before implementing it, or when you want authoritative, source-cited code free from outdated patterns. Use when building with any framework or library where correctness matters.★ 98.7k GitHub stars

More from OpenClaudia

SkillA/B Testing FrameworkOpenClaudia/openclaudia-skills · by OpenClaudiaDesign, plan, and analyze A/B tests with statistical rigor. Use when the user asks about A/B testing, split testing, experiment design, statistical significance, sample size calculation, test duration, multivariate testing, or conversion experiments. Trigger phrases include "A/B test", "split test", "experiment", "statistical significance", "sample size", "test duration", "which version wins", "conversion experiment", "hypothesis test", "variant testing".★ 705 GitHub starsSkillAffiliate Marketing ProgramOpenClaudia/openclaudia-skills · by OpenClaudiaBuild and manage an affiliate marketing program. Use when the user says "affiliate program", "affiliate marketing", "affiliate partners", "referral commissions", "affiliate network", "partner program", "affiliate tracking", or asks about creating, managing, or growing an affiliate or partner program.★ 705 GitHub starsSkillAI Citations Report GeneratorOpenClaudia/openclaudia-skills · by OpenClaudiaGenerate an AI Citations Report (GEO) for a domain — which AI-search prompts cite the site across Google AI Overview and ChatGPT, plus organic-traffic context and per-article citation coverage. Use when the user asks for an 'AI citations report', 'GEO citations report', or 'which AI prompts cite <domain>'.★ 705 GitHub starsSkillB2B Lead EnricherOpenClaudia/openclaudia-skills · by OpenClaudiaResearch and enrich B2B leads using the Apollo.io API. Use when the user says "find leads", "prospect research", "company enrichment", "find decision makers", "B2B leads", "lead research", "enrich contacts", "find VP of marketing at", or asks about finding people at specific companies or in specific roles.★ 705 GitHub starsSkillBacklink Health CheckerOpenClaudia/openclaudia-skills · by OpenClaudiaAudit a domain's backlink profile using the SemRush API. Use when the user says "audit backlinks", "check my backlinks", "backlink analysis", "link profile", "toxic links", "disavow", "link building opportunities", "referring domains", "anchor text", or asks about a site's link authority.★ 705 GitHub starsSkillBluesky Content CreatorOpenClaudia/openclaudia-skills · by OpenClaudiaCreate and manage content for Bluesky social network. Use when the user says "Bluesky post", "post to Bluesky", "Bluesky content", "Bluesky strategy", "AT Protocol", or asks about creating content for or engaging on Bluesky.★ 705 GitHub stars