2025-10-11
admin
Diperbarui 2025-10-11

Panduan Lengkap Google Search Console API untuk Analisis SEO

Pelajari cara menggunakan Google Search Console API untuk mengakses data website Anda secara terprogram. Dapatkan statistik penting, bandingkan performa, dan otomatiskan analisis SEO Anda!
Panduan Lengkap Google Search Console API untuk Analisis SEO

Google Search Console REST API Documentation

Base URL

http://YOUR_SERVER_IP:5000

Production:

https://api.yourdomain.com

Authentication

Currently, authentication is handled server-side using Google Service Account credentials. No API key required for basic usage.

For production, implement API key authentication:

# Header required (if enabled)
X-API-Key: your-secret-api-key

Response Format

All endpoints return JSON with this structure:

Success Response

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "data": { ... }
}

Error Response

{
  "success": false,
  "error": "Error message description"
}

Rate Limits

  • Google Search Console API: 1,200 requests per minute
  • This API Server: No limit (configurable)

Endpoints

1. List Sites

Get all accessible Search Console properties.

Endpoint: GET /sites

Parameters: None

Example Request:

curl -X GET "http://localhost:5000/sites"

Response:

{
  "success": true,
  "count": 4,
  "sites": [
    {
      "siteUrl": "sc-domain:example.com",
      "permissionLevel": "siteOwner"
    },
    {
      "siteUrl": "https://example.com/",
      "permissionLevel": "siteOwner"
    }
  ]
}

Response Fields:

Field Type Description count integer Total number of sites sites array List of sites with permissions siteUrl string Site URL/domain permissionLevel string Permission level (siteOwner, siteFullUser, etc) 2. Summary Statistics

Get aggregate statistics for a specified period.

Endpoint: GET /summary/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze (1-365) Example Request:

curl -X GET "http://localhost:5000/summary/sc-domain:example.com?days=30"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "data": {
    "period": "30 days",
    "start_date": "2025-09-11",
    "end_date": "2025-10-11",
    "total_clicks": 595,
    "total_impressions": 14719,
    "avg_ctr": 4.04,
    "avg_position": 7.30
  }
}

Response Fields:

Field Type Description period string Period description start_date string Start date (YYYY-MM-DD) end_date string End date (YYYY-MM-DD) total_clicks integer Total clicks in period total_impressions integer Total impressions in period avg_ctr float Average CTR percentage avg_position float Average search position 3. Period Comparison

Compare current period vs previous period of same length.

Endpoint: GET /comparison/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days per period Example Request:

curl -X GET "http://localhost:5000/comparison/sc-domain:example.com?days=30"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "data": {
    "current_period": {
      "start": "2025-09-11",
      "end": "2025-10-11",
      "clicks": 595,
      "impressions": 14719,
      "ctr": 4.04,
      "position": 7.30
    },
    "previous_period": {
      "start": "2025-08-11",
      "end": "2025-09-10",
      "clicks": 648,
      "impressions": 22554,
      "ctr": 2.87,
      "position": 11.28
    },
    "changes": {
      "clicks": -8.2,
      "impressions": -34.7,
      "ctr": 40.7,
      "position": -35.2
    }
  }
}

Response Fields:

Field Type Description current_period object Current period metrics previous_period object Previous period metrics changes object Percentage changes (positive = increase) 4. Device Breakdown

Get performance breakdown by device type.

Endpoint: GET /devices/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze Example Request:

curl -X GET "http://localhost:5000/devices/sc-domain:example.com?days=30"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "period_days": 30,
  "data": {
    "MOBILE": {
      "clicks": 367,
      "impressions": 10532,
      "ctr": 3.48,
      "position": 6.23
    },
    "DESKTOP": {
      "clicks": 224,
      "impressions": 4094,
      "ctr": 5.47,
      "position": 10.11
    },
    "TABLET": {
      "clicks": 4,
      "impressions": 93,
      "ctr": 4.30,
      "position": 5.97
    }
  }
}

Device Types:

  • MOBILE - Mobile devices
  • DESKTOP - Desktop computers
  • TABLET - Tablet devices

5. Country Analysis

Get top countries by performance.

Endpoint: GET /countries/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze limit integer No 20 Max number of countries (1-100) Example Request:

curl -X GET "http://localhost:5000/countries/sc-domain:example.com?days=30&limit=10"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "period_days": 30,
  "count": 10,
  "data": [
    {
      "country": "idn",
      "clicks": 579,
      "impressions": 13809,
      "ctr": 4.19,
      "position": 7.03
    },
    {
      "country": "mys",
      "clicks": 3,
      "impressions": 70,
      "ctr": 4.29,
      "position": 8.27
    }
  ]
}

Country Codes: ISO 3166-1 alpha-3 (e.g., idn = Indonesia, usa = United States)

6. Top Queries

Get top performing search queries.

Endpoint: GET /queries/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze limit integer No 100 Max number of queries (1-1000) Example Request:

curl -X GET "http://localhost:5000/queries/sc-domain:example.com?days=30&limit=50"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "period_days": 30,
  "count": 50,
  "data": [
    {
      "rank": 1,
      "query": "srokalan",
      "clicks": 18,
      "impressions": 336,
      "ctr": 5.36,
      "position": 1.0
    },
    {
      "rank": 2,
      "query": "apiwa",
      "clicks": 14,
      "impressions": 33,
      "ctr": 42.42,
      "position": 1.15
    }
  ]
}

Response Fields:

Field Type Description rank integer Position in top queries list query string Search query text clicks integer Total clicks impressions integer Total impressions ctr float Click-through rate (%) position float Average search position 7. Top Pages

Get top performing pages/URLs.

Endpoint: GET /pages/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze limit integer No 100 Max number of pages (1-1000) Example Request:

curl -X GET "http://localhost:5000/pages/sc-domain:example.com?days=30&limit=25"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "period_days": 30,
  "count": 25,
  "data": [
    {
      "rank": 1,
      "page": "https://example.com/article-1",
      "clicks": 88,
      "impressions": 423,
      "ctr": 20.8,
      "position": 5.83
    }
  ]
}

8. Daily Trend

Get daily performance trend.

Endpoint: GET /trend/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze Example Request:

curl -X GET "http://localhost:5000/trend/sc-domain:example.com?days=7"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "period_days": 7,
  "data_points": 7,
  "data": [
    {
      "date": "2025-10-05",
      "clicks": 20,
      "impressions": 450,
      "ctr": 4.44,
      "position": 7.2
    },
    {
      "date": "2025-10-06",
      "clicks": 25,
      "impressions": 520,
      "ctr": 4.81,
      "position": 6.8
    }
  ]
}

Use Cases:

  • Identify traffic patterns
  • Detect spikes or drops
  • Monitor consistency
  • Seasonality analysis

9. Page Detail

Get detailed analysis for a specific page/URL.

Endpoint: GET /page-detail/<site_url>

Parameters:

Parameter Type Required Default Description page_url string Yes - Full URL of the page to analyze days integer No 30 Number of days to analyze Example Request:

curl -X GET "http://localhost:5000/page-detail/sc-domain:example.com?page_url=https://example.com/article&days=30"

Response:

{
  "success": true,
  "site_url": "sc-domain:example.com",
  "data": {
    "page_url": "https://example.com/article",
    "period": "30 days",
    "total_queries": 45,
    "queries": [
      {
        "query": "keyword example",
        "clicks": 12,
        "impressions": 89,
        "ctr": 13.48,
        "position": 4.2
      }
    ]
  }
}

Use Cases:

  • Analyze which queries drive traffic to specific page
  • Optimize page for better-performing queries
  • Identify keyword opportunities

10. Full Report

Get comprehensive report with all metrics.

Endpoint: GET /full-report/<site_url>

Parameters:

Parameter Type Required Default Description days integer No 30 Number of days to analyze Example Request:

curl -X GET "http://localhost:5000/full-report/sc-domain:example.com?days=30"

Response:

{
  "success": true,
  "data": {
    "site_url": "sc-domain:example.com",
    "generated_at": "2025-10-11T15:30:45",
    "period_days": 30,
    "summary": { ... },
    "comparison": { ... },
    "devices": { ... },
    "top_countries": [ ... ],
    "daily_trend": [ ... ],
    "top_queries": [ ... ],
    "top_pages": [ ... ]
  }
}

Includes:

  • Summary statistics
  • Period comparison
  • Device breakdown
  • Top 20 countries
  • Daily trend (30 days)
  • Top 50 queries
  • Top 50 pages

Error Codes

HTTP Code Error Type Description 200 Success Request successful 400 Bad Request Invalid parameters 401 Unauthorized Invalid or missing API key 404 Not Found Endpoint not found 500 Internal Error Server error Error Response Example:

{
  "success": false,
  "error": "Missing required parameter: page_url"
}

Code Examples

Python (requests)

import requests

BASE_URL = "http://localhost:5000"
SITE_URL = "sc-domain:example.com"

# Get summary
response = requests.get(f"{BASE_URL}/summary/{SITE_URL}?days=30")
data = response.json()
print(f"Total Clicks: {data['data']['total_clicks']}")

# Get top queries
response = requests.get(f"{BASE_URL}/queries/{SITE_URL}?days=7&limit=10")
queries = response.json()['data']
for q in queries:
    print(f"{q['rank']}. {q['query']} - {q['clicks']} clicks")

JavaScript (fetch)

const BASE_URL = 'http://localhost:5000';
const SITE_URL = 'sc-domain:example.com';

// Get comparison
fetch(`${BASE_URL}/comparison/${SITE_URL}?days=30`)
  .then(res => res.json())
  .then(data => {
    const changes = data.data.changes;
    console.log(`Clicks change: ${changes.clicks}%`);
  });

// Get devices
async function getDevices() {
  const res = await fetch(`${BASE_URL}/devices/${SITE_URL}?days=30`);
  const data = await res.json();
  console.log(data.data.MOBILE);
}

PHP (cURL)

<?php
$base_url = "http://localhost:5000";
$site_url = "sc-domain:example.com";

// Get summary
$url = "{$base_url}/summary/{$site_url}?days=30";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);

echo "Total Clicks: " . $data['data']['total_clicks'];
curl_close($ch);
?>

cURL (Command Line)

# Get sites
curl -X GET "http://localhost:5000/sites"

# Get summary with pretty print
curl -X GET "http://localhost:5000/summary/sc-domain:example.com?days=30" | jq '.'

# Get top queries and save to file
curl -X GET "http://localhost:5000/queries/sc-domain:example.com?days=30&limit=100" > queries.json

# Full report
curl -X GET "http://localhost:5000/full-report/sc-domain:example.com?days=30" | jq '.data' > report.json

Google Apps Script

function getGSCData() {
  const BASE_URL = 'http://your-server:5000';
  const SITE_URL = 'sc-domain:example.com';
  
  // Get summary
  const url = `${BASE_URL}/summary/${SITE_URL}?days=30`;
  const response = UrlFetchApp.fetch(url);
  const data = JSON.parse(response.getContentText());
  
  // Write to Google Sheets
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange('A1').setValue('Total Clicks');
  sheet.getRange('B1').setValue(data.data.total_clicks);
}

Best Practices

1. Caching

Implement caching to reduce API calls:

import time
from functools import lru_cache

@lru_cache(maxsize=100)
def get_cached_summary(site_url, days, timestamp):
    # timestamp untuk invalidate cache setiap 1 jam
    return requests.get(f"{BASE_URL}/summary/{site_url}?days={days}").json()

# Usage
data = get_cached_summary(site_url, 30, int(time.time() / 3600))

2. Error Handling

Always handle errors gracefully:

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    data = response.json()
    
    if not data['success']:
        print(f"API Error: {data.get('error')}")
    else:
        # Process data
        pass
except requests.exceptions.Timeout:
    print("Request timeout")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

3. Rate Limiting

Respect rate limits:

import time

def make_request_with_retry(url, max_retries=3):
    for i in range(max_retries):
        try:
            response = requests.get(url)
            if response.status_code == 429:  # Too Many Requests
                time.sleep(2 ** i)  # Exponential backoff
                continue
            return response.json()
        except Exception as e:
            if i == max_retries - 1:
                raise
            time.sleep(1)

4. Batch Processing

For multiple sites:

sites = ['sc-domain:site1.com', 'sc-domain:site2.com']

for site in sites:
    summary = get_summary(site, days=30)
    print(f"{site}: {summary['data']['total_clicks']} clicks")
    time.sleep(1)  # Rate limiting

Deployment

Production Checklist

  • [ ] Enable HTTPS with SSL certificate
  • [ ] Implement API key authentication
  • [ ] Set up rate limiting
  • [ ] Configure CORS properly
  • [ ] Enable logging and monitoring
  • [ ] Set up error alerting
  • [ ] Use environment variables for sensitive data
  • [ ] Deploy behind reverse proxy (Nginx)
  • [ ] Enable request caching
  • [ ] Set up auto-restart (systemd/supervisor)

Nginx Configuration Example

server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://localhost:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # CORS headers
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
    }
}

Support & Resources

  • API Source Code: [GitHub Repository]
  • Issues & Bugs: [GitHub Issues]
  • Google Search Console API Docs: https://developers.google.com/webmaster-tools
  • Rate Limits: https://developers.google.com/webmaster-tools/limits

Last Updated: October 11, 2025

API Version: 2.0

Maintained by: Your Team Name

blog teknologi programming admin

Artikel Terkait