Skip to content

Latest commit

 

History

History
576 lines (476 loc) · 15.3 KB

File metadata and controls

576 lines (476 loc) · 15.3 KB

Keyword API Usage Examples

Quick examples to get you started with the Keyword Suggestions API.

JavaScript/Fetch Examples

1. Get Basic Keyword Suggestions

async function getKeywordSuggestions(keyword) {
  const response = await fetch('/api/keywords/suggestions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`, // or 'X-API-KEY': apiKey for WordPress
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keyword: keyword,
      limit: 20,
      country: 'us',
      language: 'en'
    })
  });

  const data = await response.json();

  if (data.success) {
    console.log(`Found ${data.data.total} suggestions for "${keyword}"`);
    data.data.suggestions.forEach(suggestion => {
      console.log(`- ${suggestion.keyword} (Volume: ${suggestion.search_volume}, Difficulty: ${suggestion.difficulty})`);
    });
  }

  return data;
}

// Usage
getKeywordSuggestions('seo tools');

2. Get Related Keywords with Variations

async function getRelatedKeywords(keyword) {
  const response = await fetch('/api/keywords/related', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keyword: keyword,
      limit: 50,
      country: 'us'
    })
  });

  const data = await response.json();

  if (data.success) {
    // Group by search volume ranges
    const highVolume = data.data.related_keywords.filter(k => k.search_volume > 5000);
    const mediumVolume = data.data.related_keywords.filter(k => k.search_volume >= 1000 && k.search_volume <= 5000);
    const lowVolume = data.data.related_keywords.filter(k => k.search_volume < 1000);

    console.log(`High volume keywords: ${highVolume.length}`);
    console.log(`Medium volume keywords: ${mediumVolume.length}`);
    console.log(`Low volume keywords: ${lowVolume.length}`);
  }

  return data;
}

// Usage
getRelatedKeywords('content marketing');

3. Analyze a Specific Keyword

async function analyzeKeyword(keyword) {
  const response = await fetch('/api/keywords/analyze', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keyword: keyword,
      country: 'us',
      language: 'en'
    })
  });

  const data = await response.json();

  if (data.success) {
    const analysis = data.data;
    console.log(`Keyword: ${analysis.keyword}`);
    console.log(`Search Volume: ${analysis.search_volume}`);
    console.log(`Difficulty: ${analysis.difficulty}/100`);
    console.log(`Opportunity Score: ${analysis.opportunity_score}/100`);
    console.log(`Recommendation: ${analysis.recommendation}`);
    console.log(`Related keywords: ${analysis.related_keywords.length}`);
  }

  return data;
}

// Usage
analyzeKeyword('email marketing');

4. Batch Analyze Multiple Keywords

async function batchAnalyzeKeywords(keywords) {
  const response = await fetch('/api/keywords/batch-analyze', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keywords: keywords,
      country: 'us',
      language: 'en'
    })
  });

  const data = await response.json();

  if (data.success) {
    console.log(`Analyzed ${data.data.total} keywords`);
    console.log(`Best opportunity: ${data.data.best_opportunity.keyword} (Score: ${data.data.best_opportunity.opportunity_score})`);

    // Display all results sorted by opportunity
    data.data.results.forEach((result, index) => {
      console.log(`${index + 1}. ${result.keyword}`);
      console.log(`   Opportunity: ${result.opportunity_score}/100`);
      console.log(`   Volume: ${result.search_volume}, Difficulty: ${result.difficulty}`);
      console.log(`   ${result.recommendation}`);
    });
  }

  return data;
}

// Usage
batchAnalyzeKeywords([
  'seo audit',
  'keyword research',
  'backlink analysis',
  'content optimization'
]);

5. Find Best Keywords from a Topic

async function findBestKeywords(topic, minOpportunityScore = 50) {
  // Step 1: Get related keywords
  const relatedResponse = await fetch('/api/keywords/related', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keyword: topic,
      limit: 30,
      country: 'us'
    })
  });

  const relatedData = await relatedResponse.json();

  if (!relatedData.success) {
    return [];
  }

  // Step 2: Batch analyze the keywords
  const keywords = relatedData.data.related_keywords.map(k => k.keyword);

  const analysisResponse = await fetch('/api/keywords/batch-analyze', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      keywords: keywords.slice(0, 20), // Limit to 20 for batch
      country: 'us'
    })
  });

  const analysisData = await analysisResponse.json();

  if (analysisData.success) {
    // Filter by minimum opportunity score
    const goodKeywords = analysisData.data.results.filter(
      k => k.opportunity_score >= minOpportunityScore
    );

    console.log(`Found ${goodKeywords.length} high-opportunity keywords`);
    return goodKeywords;
  }

  return [];
}

// Usage
findBestKeywords('wordpress plugins', 60).then(keywords => {
  console.log('Best keywords to target:', keywords);
});

PHP Examples

1. Using the Service Directly

use App\Services\KeywordSuggestionService;

// In a controller or command
$keywordService = app(KeywordSuggestionService::class);

// Get suggestions
$suggestions = $keywordService->getSuggestions('seo tools', [
    'country' => 'us',
    'language' => 'en',
    'limit' => 20
]);

foreach ($suggestions as $suggestion) {
    echo "{$suggestion['keyword']} - Volume: {$suggestion['search_volume']}\n";
}

2. Analyze Multiple Keywords

use App\Services\KeywordSuggestionService;

$keywordService = app(KeywordSuggestionService::class);

$keywords = ['email marketing', 'seo tools', 'content writing'];
$results = [];

foreach ($keywords as $keyword) {
    $results[] = $keywordService->analyzeKeyword($keyword);
}

// Sort by opportunity score
usort($results, fn($a, $b) => $b['opportunity_score'] <=> $a['opportunity_score']);

echo "Best keyword: {$results[0]['keyword']} (Score: {$results[0]['opportunity_score']})\n";

3. WordPress Plugin Integration

// In your WordPress plugin
function wegenius_get_keyword_suggestions($keyword) {
    $api_key = get_option('wegenius_api_key');
    $api_url = get_option('wegenius_api_url');

    $response = wp_remote_post($api_url . '/api/ai/keywords/suggestions', [
        'headers' => [
            'X-API-KEY' => $api_key,
            'Content-Type' => 'application/json',
        ],
        'body' => json_encode([
            'keyword' => $keyword,
            'limit' => 15,
            'country' => 'us'
        ]),
        'timeout' => 30
    ]);

    if (is_wp_error($response)) {
        return [];
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if ($data['success']) {
        return $data['data']['suggestions'];
    }

    return [];
}

// Usage
$suggestions = wegenius_get_keyword_suggestions('best wordpress themes');
foreach ($suggestions as $suggestion) {
    echo "<li>{$suggestion['keyword']} ({$suggestion['search_volume']} searches/month)</li>";
}

Python Example

import requests
import json

class KeywordAPI:
    def __init__(self, base_url, token):
        self.base_url = base_url
        self.token = token
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

    def get_suggestions(self, keyword, limit=20):
        response = requests.post(
            f'{self.base_url}/api/keywords/suggestions',
            headers=self.headers,
            json={
                'keyword': keyword,
                'limit': limit,
                'country': 'us',
                'language': 'en'
            }
        )
        return response.json()

    def analyze_keyword(self, keyword):
        response = requests.post(
            f'{self.base_url}/api/keywords/analyze',
            headers=self.headers,
            json={
                'keyword': keyword,
                'country': 'us',
                'language': 'en'
            }
        )
        return response.json()

    def find_easy_keywords(self, topic, max_difficulty=40):
        """Find easy-to-rank keywords on a topic"""
        related = requests.post(
            f'{self.base_url}/api/keywords/related',
            headers=self.headers,
            json={'keyword': topic, 'limit': 50}
        ).json()

        if not related['success']:
            return []

        # Filter by difficulty
        easy_keywords = [
            k for k in related['data']['related_keywords']
            if k['difficulty'] <= max_difficulty and k['search_volume'] > 100
        ]

        # Sort by search volume
        easy_keywords.sort(key=lambda x: x['search_volume'], reverse=True)

        return easy_keywords

# Usage
api = KeywordAPI('https://your-domain.com', 'your-token')

# Get suggestions
suggestions = api.get_suggestions('digital marketing')
print(f"Found {suggestions['data']['total']} suggestions")

# Find easy keywords
easy_keywords = api.find_easy_keywords('wordpress seo', max_difficulty=35)
for keyword in easy_keywords[:10]:
    print(f"{keyword['keyword']} - Volume: {keyword['search_volume']}, Difficulty: {keyword['difficulty']}")

React Component Example

import { useState } from 'react';

function KeywordResearch() {
  const [keyword, setKeyword] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [analysis, setAnalysis] = useState(null);

  const fetchSuggestions = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/keywords/suggestions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ keyword, limit: 20 })
      });

      const data = await response.json();
      if (data.success) {
        setSuggestions(data.data.suggestions);
      }
    } catch (error) {
      console.error('Error fetching suggestions:', error);
    }
    setLoading(false);
  };

  const analyzeKeyword = async (kw) => {
    try {
      const response = await fetch('/api/keywords/analyze', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ keyword: kw })
      });

      const data = await response.json();
      if (data.success) {
        setAnalysis(data.data);
      }
    } catch (error) {
      console.error('Error analyzing keyword:', error);
    }
  };

  return (
    <div className="keyword-research">
      <div className="search-box">
        <input
          type="text"
          value={keyword}
          onChange={(e) => setKeyword(e.target.value)}
          placeholder="Enter a keyword..."
        />
        <button onClick={fetchSuggestions} disabled={loading}>
          {loading ? 'Loading...' : 'Get Suggestions'}
        </button>
      </div>

      {suggestions.length > 0 && (
        <div className="suggestions">
          <h3>Keyword Suggestions</h3>
          <table>
            <thead>
              <tr>
                <th>Keyword</th>
                <th>Volume</th>
                <th>Difficulty</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              {suggestions.map((suggestion, index) => (
                <tr key={index}>
                  <td>{suggestion.keyword}</td>
                  <td>{suggestion.search_volume.toLocaleString()}</td>
                  <td>
                    <span className={`difficulty-${getDifficultyLevel(suggestion.difficulty)}`}>
                      {suggestion.difficulty}/100
                    </span>
                  </td>
                  <td>
                    <button onClick={() => analyzeKeyword(suggestion.keyword)}>
                      Analyze
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {analysis && (
        <div className="analysis">
          <h3>Keyword Analysis: {analysis.keyword}</h3>
          <div className="metrics">
            <div className="metric">
              <label>Search Volume</label>
              <strong>{analysis.search_volume.toLocaleString()}</strong>
            </div>
            <div className="metric">
              <label>Difficulty</label>
              <strong>{analysis.difficulty}/100</strong>
            </div>
            <div className="metric">
              <label>Opportunity Score</label>
              <strong>{analysis.opportunity_score}/100</strong>
            </div>
          </div>
          <div className="recommendation">
            <p>{analysis.recommendation}</p>
          </div>
        </div>
      )}
    </div>
  );
}

function getDifficultyLevel(difficulty) {
  if (difficulty < 30) return 'easy';
  if (difficulty < 60) return 'medium';
  return 'hard';
}

export default KeywordResearch;

Common Use Cases

1. Content Planning Workflow

async function planContentAround(topic) {
  // Get related keywords
  const related = await getRelatedKeywords(topic);

  // Batch analyze top 20
  const topKeywords = related.data.related_keywords.slice(0, 20).map(k => k.keyword);
  const analysis = await batchAnalyzeKeywords(topKeywords);

  // Filter for good opportunities (score > 50) and reasonable volume
  const targetKeywords = analysis.data.results.filter(
    k => k.opportunity_score > 50 && k.search_volume > 500
  );

  console.log(`Target these ${targetKeywords.length} keywords in your content:`);
  targetKeywords.forEach(k => {
    console.log(`- ${k.keyword} (Volume: ${k.search_volume}, Score: ${k.opportunity_score})`);
  });
}

2. Competitor Keyword Gap Analysis

async function findKeywordGaps(myKeywords, topic) {
  const allSuggestions = await getRelatedKeywords(topic);

  const gaps = allSuggestions.data.related_keywords.filter(
    suggestion => !myKeywords.includes(suggestion.keyword)
  );

  console.log(`Found ${gaps.length} keyword gaps to explore`);
  return gaps;
}

3. Low-Hanging Fruit Finder

async function findLowHangingFruit(topic) {
  const related = await getRelatedKeywords(topic);
  const keywords = related.data.related_keywords.map(k => k.keyword).slice(0, 30);

  const analysis = await batchAnalyzeKeywords(keywords);

  // Low difficulty (<40), decent volume (>500), high opportunity (>60)
  const lowHanging = analysis.data.results.filter(
    k => k.difficulty < 40 && k.search_volume > 500 && k.opportunity_score > 60
  );

  return lowHanging;
}