◆IKORG

← Practice · September 8, 2026

How to connect AI to Yandex Webmaster and stop opening the interface

Get a token, call the Webmaster API from the terminal, put recrawling and monitoring on cron, and leave troubleshooting to Claude Code: ask “what’s going on with the site?” and get a diagnosis and a fix.

10 min readtools

I have twenty-two sites in Yandex Webmaster. Opening each site’s interface once a week means two hours of clicking, and I don’t do it. Which means I don’t notice pages dropping out of search or diagnostic warnings in time: I find out when things already need fixing.

Meanwhile, Webmaster returns the same information through its API in a second. With an AI assistant that can run curl, I don’t need the interface at all: “what’s going on with eden96?” — and a minute later I have a diagnosis in the terminal, rather than a report.

Below is exactly what I have set up and running every morning.

What you end up with

# I write in Claude Code:
# “Webmaster is complaining about eden96, look into it”
#
# the session then:
#   1. fetches summary and diagnostics through the API
#   2. compares pages in search against the sitemap
#   3. curls suspicious URLs and finds redirect loops
#   4. fixes .htaccess in the repository, rebuilds, deploys
#   5. submits the fixed URLs for recrawling

Plus two scripts on cron: one uses up the daily recrawl quota, the other records metrics once a day and raises an alert if anything drops.

Step 1. The token

The Webmaster API uses an OAuth token. You get the token through a single link:

https://oauth.yandex.ru/authorize?response_type=token&client_id=ba16a05cf7134a29aadd139e8c12c891

This is the ID of the standard “Yandex Webmaster API” application — it has no secret, and you don’t need to register your own. Open the link, sign in to the account that owns the sites, and Yandex displays the token right on the page. Copy it into a file:

umask 077
echo 'INSERT_TOKEN' > ~/.yandex_webmaster_token

Three things worth knowing in advance.

The token belongs to the account, not the site. One file grants access to all verified hosts at once: twenty-two in my case, from any project and any session.

It lasts six months. Issued on September fifth — expires in early March. The telltale sign is HTTP 401 on every request. A token from a completely different account or a malformed token returns 403, by the way, so any 4xx failure on a request that worked yesterday is about the token, not the site. Only a person can renew the token: same link, same sign-in. The AI can’t help here, and that’s how it should be.

Do not print the token value in the terminal. All the examples below read it from a file. If an AI session does write it to a log, get a new one.

Step 2. Your user_id and the site’s host_id

All API URLs start with a numeric user ID:

T=$(cat ~/.yandex_webmaster_token)
curl -s -H "Authorization: OAuth $T" https://api.webmaster.yandex.net/v4/user/
# {"user_id":79452740}

Next, the host list. Here comes the first pitfall:

U=79452740
curl -s -H "Authorization: OAuth $T" "https://api.webmaster.yandex.net/v4/user/$U/hosts/"
{"host_id": "https:eden96.ru:443", "verified": true, "ascii_host_url": "https://eden96.ru/"}
{"host_id": "https:xn--80aahsbi1ccix.xn--p1ai:443", "unicode_host_url": "https://играйсразу.рф/"}

host_id is not a URL but a string in the form scheme:domain:port. Insert it into the URL as is, without urlencode. Encode the colons and you get 404 on every request and half an hour wasted. The Cyrillic domain is already in punycode — pass it that way.

Set up a variable; all the commands below use it:

H="https:eden96.ru:443"
B="https://api.webmaster.yandex.net/v4/user/$U/hosts/$H"

Step 3. What to read

Four requests cover ninety percent of the questions.

Summary — how many pages are in search, how many are excluded, and the site quality index:

curl -s -H "Authorization: OAuth $T" "$B/summary/"
# {"sqi":30,"excluded_pages_count":1,"searchable_pages_count":96,"site_problems":{"POSSIBLE_PROBLEM":1}}

Diagnostics — the same “complaints” you see in the interface:

curl -s -H "Authorization: OAuth $T" "$B/diagnostics/" | python3 -m json.tool

The structure matters here. problems comes back as a dictionary, not a list, keyed by problem code. It includes every problem Webmaster knows about, including ones the site has never had:

"DOCUMENTS_MISSING_DESCRIPTION": {
    "severity": "POSSIBLE_PROBLEM",
    "state": "PRESENT",
    "last_state_update": "2026-08-23T10:24:03.804+03:00"
},
"SLOW_AVG_RESPONSE_TIME": {
    "severity": "CRITICAL",
    "state": "ABSENT",
    "last_state_update": null
}

Only state: PRESENT means an active problem. ABSENT means resolved or never encountered. And always check last_state_update: Webmaster does not update diagnostics every day, and the report often describes a state that no longer exists. If the last update predates your deployment, the problem is probably already fixed; the crawler just hasn’t checked again.

Pages in search — with the title and last crawl date:

curl -s -H "Authorization: OAuth $T" "$B/search-urls/in-search/samples/?limit=100"

Events — what appeared, what dropped out, and most importantly, why:

curl -s -H "Authorization: OAuth $T" "$B/search-urls/events/samples/?limit=100"
{"url": "https://eden96.ru/category/esteticheska-stomatologiya/restavraciya-zubov/",
 "event": "REMOVED_FROM_SEARCH",
 "excluded_url_status": "REDIRECT_NOTSEARCHABLE",
 "target_url": "http://eden96.ru/"}

That record is a diagnosis on its own. A page from the old CMS dropped out because it redirects, and it redirects to http://, even though the site has been on https:// for a long time. More on that below.

Step 4. Comparing against the sitemap

The quickest way to find the cause of a complaint is to subtract one set from another instead of reading reports. Take the URLs from search and the URLs from sitemap.xml:

curl -s -H "Authorization: OAuth $T" "$B/search-urls/in-search/samples/?limit=500" \
  | python3 -c "import json,sys; print('\n'.join(s['url'] for s in json.load(sys.stdin)['samples']))" \
  | sort > /tmp/in-search.txt

grep -o '<loc>[^<]*' dist/sitemap.xml | sed 's/<loc>//' | sort > /tmp/sitemap.txt

comm -23 /tmp/in-search.txt /tmp/sitemap.txt   # in search but not in the sitemap: junk from the old CMS
comm -13 /tmp/in-search.txt /tmp/sitemap.txt   # in the sitemap but not in search: the crawler cannot see them

On eden96, the first difference revealed leftovers from WordPress: /category/..., /tag/..., /page/2/. The site had changed platforms twice, but the search engine remembered all of it and kept it in the index because the URLs weren’t returning anything meaningful.

Step 5. Check URLs with curl, not by eye

Here comes the second pitfall, and it is costly. On sites hosted by Beget, the first request without a cookie gets a 274-byte JavaScript stub with a 200 status code, rather than the page. A browser gets through it without you noticing; curl does not:

curl -s -o /dev/null -w '%{http_code} %{size_download}\n' https://eden96.ru/
# 200 274        ← this is not the site, it is the stub
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' -b "beget=begetok" https://eden96.ru/
# 200 48013      ← this is the site

Without the cookie, any diagnosis will be wrong: all pages “return 200,” there are “no redirects,” yet Webmaster keeps complaining. So I have a rule written into the AI’s instructions: always use -b "beget=begetok" when curling a site on Beget.

The second check is for loops and unnecessary hops:

curl -s -o /dev/null -L -b "beget=begetok" \
  -w '%{num_redirects} %{url_effective}\n' https://eden96.ru/category/novosti/

If there are two hops instead of one, check .htaccess. Behind Beget’s proxy, Apache sees the request as http, so it expands a relative redirect target to http://. The http→https rule then kicks in, adding an extra hop. Two things fix this: write redirect targets as absolute URLs with https://, and put the http→https rule last in the file.

Step 6. Fix things in the repository and return 410

On Astro sites, .htaccess lives in public/ and goes to production with the build. Edit it on production over ssh and you lose the change on the next deployment. Everything below happens in the repository.

With junk URLs from the old CMS, the temptation is to 301 everything to the homepage. Don’t. The search engine treats a 301 to an unrelated homepage as a soft 404 and keeps the URL in the index for months, while pages that have moved keep showing up as “redirect.” The correct approach: if it has a new URL, 301 to that exact URL; if it no longer exists, return 410 Gone:

# --- Pages removed along with WordPress: 410 Gone ---
# Yandex and Google drop 410s from the index faster than 301s to the homepage
RewriteRule ^author(/|$)      - [G,L]
RewriteRule ^bez-rubriki(/|$) - [G,L]

# --- Moved pages: absolute https targets only ---
RewriteRule ^novosti/?$ https://eden96.ru/o-klinike/novosti/ [R=301,L]
RewriteRule ^protezirovanie/?$ https://eden96.ru/protezirovanie-zubov/ [R=301,L]

# --- WordPress categories: /category/<section>/ -> the section with the same name, if it exists ---
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^category/([^/]+)/?$ https://eden96.ru/$1/ [R=301,L]

# --- http -> https: strictly last ---

After deployment, check that every URL in the sitemap returns 200 and that there are no loops. Only then is it “done.”

Step 7. Recrawling and its quota

Fixing things is not enough — the crawler needs to visit. Otherwise, the diagnostic warning stays until the next scheduled crawl, which means weeks. A recrawl request:

curl -s -X POST -H "Authorization: OAuth $T" -H "Content-Type: application/json" \
     -d '{"url":"https://eden96.ru/o-klinike/novosti/"}' "$B/recrawl/queue/"

The request quota:

curl -s -H "Authorization: OAuth $T" "$B/recrawl/quota/"
# {"daily_quota":560,"quota_remainder":560}

Two details. Each site has its own quota: eden96 gets 560 URLs a day, играйсразу.рф gets 150, another project gets 850; Yandex calculates it, and you cannot influence it. And it does not accumulate: anything unused that day expires. The second point leads straight to cron.

Daily recrawling within the quota

играйсразу.рф has three and a half thousand pages and 150 requests a day. Every morning, recrawl_daily.py checks the remaining quota and submits exactly as many URLs as allowed, moving through a circular queue:

TOKEN = open(os.path.expanduser('~/.yandex_webmaster_token')).read().strip()
BASE = f'https://api.webmaster.yandex.net/v4/user/{USER}/hosts/{HOST_ID}'

def api(method, path, data=None):
    req = urllib.request.Request(BASE + path, data=data, method=method,
        headers={'Authorization': f'OAuth {TOKEN}', 'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode('utf-8') or '{}')

q = api('GET', '/recrawl/quota/')
left = q.get('quota_remainder', 0)
if left <= 0:
    print('Today’s quota is exhausted.'); return

queue = build_queue()            # listings first, then the 3000 most-read pages
st = load_state()                # {'pos': 450, 'circles': 0} in a small json file
pos = st['pos'] % len(queue)
batch = [queue[(pos + i) % len(queue)] for i in range(left)]

ok = 0
for u in batch:
    try:
        api('POST', '/recrawl/queue/', json.dumps({'url': u}).encode('utf-8'))
        ok += 1
    except Exception:
        break                    # quota exhausted or request rejected — no point hammering away
st['pos'] = (pos + ok) % len(queue)
save_state(st)

The queue is built from the source files: first the listings through which the crawler finds everything else, then pages in descending order of views. The position is stored in a file, and when the list ends, it starts over — submitting again is not spam, it is a standard mechanism, and the pages have time to change by then. A full pass through the front of the queue takes twenty days.

One line in cron:

40 6 * * * cd ~/accords && timeout 900 python3 tools/recrawl_daily.py >> tools/_recrawl/cron.log 2>&1

Today’s log:

2026-09-07  quota: 150 per day, 150 available
Queue: 3005 URLs, position 300. Submitting 150.
Submitted for recrawling: 150. Next position: 450.

Monitoring metrics

The second script, webmaster_watch.py, fills this gap: I won’t check manually once a week, but it checks every day. Once a day, it fetches the summary, writes a row to the history, and compares it with the past week:

s = api('/summary/')
searchable, excluded, sqi = s['searchable_pages_count'], s['excluded_pages_count'], s['sqi']
alerts = []

# 1) active diagnostic problems — PRESENT only
for name, p in api('/diagnostics/').get('problems', {}).items():
    if p.get('state') == 'PRESENT':
        mark = '🔴' if p.get('severity') in ('FATAL', 'CRITICAL') else '🟡'
        alerts.append(f'{mark} diagnostics: {name}, since {(p.get("last_state_update") or "?")[:10]}')

# 2) a drop in pages in search relative to the weekly average
prev = [r[1] for r in history()[-7:]]
if prev and searchable < sum(prev) / len(prev) * 0.7:
    alerts.append(f'🔴 in search: {searchable} — down from an average of {sum(prev)/len(prev):.0f}')

# 3) sitemap errors
for sm in api('/sitemaps/').get('sitemaps', []):
    if sm.get('errors_count'):
        alerts.append(f'🔴 sitemap: {sm["errors_count"]} errors')

# 4) quota is not being used — a silent loss
q = api('/recrawl/quota/')
if q.get('quota_remainder') == q.get('daily_quota'):
    alerts.append(f'🟡 recrawl quota is not being used: {q["daily_quota"]} per day')

The result is two files. history.tsv: one row per day, with the date, pages in search, excluded pages, and site quality index. alerts.log: deviations only. An empty alerts file means “everything is fine,” and reading it once a week is enough — or asking the AI to take a look.

2026-09-05  501 27  10
2026-09-06  501 27  10
2026-09-07  688 21  10

The drop threshold is thirty percent, no lower: Yandex regularly reassesses a young site, and the metric fluctuates by ten to fifteen percent on its own. Raise an alert at every fluctuation and you will stop reading the log after a week.

What the API does not have

To be clear, so you don’t waste time looking.

Page removal. The interface has a “Remove URL” section; API v4 does not. If you need to remove a URL from search urgently rather than wait for the crawler to see the 410, you have to do it manually.

Regions. Assigning a site to a region is also only available in the interface.

A complete list of pages. The samples methods return a sample, at most a few hundred per request, rather than all pages. That is enough to compare against a sitemap with a hundred pages; with ten thousand, you are comparing a sample.

Everything else — summary, diagnostics, events, sitemaps, recrawling, indexing history — is available and works without surprises.

What the AI does here

A person can run all the commands above. The difference is that they won’t do it once a week for twenty-two sites. I certainly won’t.

So a condensed version of these instructions lives in my ~/.claude/CLAUDE.md — the file Claude Code reads at the start of every session. It contains the token file path, user_id, request templates, the Beget cookie rule, the 410 rule, and an eight-point procedure for investigating a complaint. After that, the conversation looks like this:

— What’s going on with eden96?

— There are 96 pages in search, 1 excluded, and one active problem: DOCUMENTS_MISSING_DESCRIPTION, flagged on August 23. Compared against the sitemap: all 88 URLs in the sitemap are in search. Eight extra URLs in search are WordPress leftovers; all return 410 after the September 5 fixes, and the crawler has not checked them again yet. No deviations, nothing needs doing.

A minute instead of half an hour. And when there is a real complaint, the session runs through the entire procedure itself: fetches diagnostics, compares against the sitemap, curls suspicious URLs with the right cookie, finds a redirect loop, edits .htaccess in the repository, rebuilds, deploys, checks that all URLs return 200, and submits the fixes for recrawling. On eden96, that took one evening, including deployment; doing it manually, I would have spent that evening just reading reports.

Where the assistant saves hours: checking all sites at once, comparing sets, reading the dictionary of problems and their dates, checking a hundred URLs with curl, writing redirect rules from a list of junk URLs, submitting recrawl requests in batches.

Where a person decides, and the instructions say this explicitly:

And one rule I learned from the first attempts: the AI needs a procedure, not just access. A token without instructions about the Beget cookie led to a confident “all pages return 200, no problems” — while Webmaster had an active complaint. Eight points in an instructions file are worth more than any access.

Pitfalls, briefly