Code

Python: API Calls to Generate Content

Automate content writing at scale using Python API calls. Generate SEO-optimized content programmatically with retry logic and error handling.

Python: API Calls to Generate Content

Overview

Automate content generation for your programmatic SEO pages using Python API calls. This example shows how to call AI APIs (OpenAI, xAI) to generate content at scale with proper error handling and retry logic.

The Code

import os
import json
import requests
import time
from typing import Optional

# Configuration from environment
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions'
OPENAI_API_MODEL = os.environ.get('OPENAI_API_MODEL', 'gpt-4o-mini')

def call_openai_api(messages: list, max_retries: int = 3) -> Optional[dict]:
    """
    Call OpenAI API with retry logic and error handling.
    Returns parsed JSON response or None on failure.
    """
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": OPENAI_API_MODEL,
        "messages": messages,
        "temperature": 0.7,
        "max_tokens": 16000
    }
    
    for attempt in range(max_retries):
        try:
            response = requests.post(
                OPENAI_API_URL,
                headers=headers,
                json=payload,
                timeout=180  # 3 min timeout
            )
            response.raise_for_status()
            
            result = response.json()
            content = result["choices"][0]["message"]["content"]
            
            # Clean up response - remove markdown code blocks if present
            content = content.strip()
            if content.startswith("```json"):
                content = content[7:]
            if content.startswith("```"):
                content = content[3:]
            if content.endswith("```"):
                content = content[:-3]
            content = content.strip()
            
            # Parse JSON
            return json.loads(content)
            
        except json.JSONDecodeError as e:
            print(f"JSON parse error (attempt {attempt + 1}): {e}")
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
                
        except requests.exceptions.RequestException as e:
            print(f"API error (attempt {attempt + 1}): {e}")
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)
    
    return None

def generate_content(entity_data: dict, prompt_template: str) -> Optional[dict]:
    """
    Generate content for a single entity using AI API.
    """
    messages = [
        {"role": "system", "content": "You are an expert SEO content writer."},
        {"role": "user", "content": prompt_template.format(**entity_data)}
    ]
    
    return call_openai_api(messages)

# Example usage
entity = {
    "name": "Notion",
    "category": "Productivity Tools",
    "features": ["Notes", "Databases", "Collaboration"]
}

prompt = """Write SEO-optimized content about {name}, a {category}.
Include these features: {features}.
Return JSON with: title, meta_description, content_html.
"""

result = generate_content(entity, prompt)
if result:
    print(f"Generated: {result.get('title')}")
else:
    print("Failed to generate content")

Key Features

  • Retry Logic: Exponential backoff on failures
  • Error Handling: Graceful handling of API errors and JSON parsing
  • Response Cleaning: Removes markdown code blocks from AI responses
  • Timeout Protection: Prevents hanging requests
  • Environment Variables: Secure API key management

Scaling Tips

  • Use async/await for concurrent requests
  • Implement rate limiting to respect API limits
  • Cache responses for similar entities
  • Batch process multiple entities
  • Monitor API usage and costs

More Templates