Code Examples

Real-world code examples in JavaScript, Python, and PHP.

Interactive Code Generator

Configure your API request and instantly generate code snippets in your favorite language. Simply enter your target URL, choose an extraction mode, and add your API key to get started.

API Code Generator
Configure your request and get code snippets in your favorite language
const response = await fetch('https://api.injectapi.com/api/extract', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    url: 'https://example.com',
    mode: 'product',
    extract: true
  })
});

const data = await response.json();
console.log(data);

šŸ’” Getting Started:

  1. Sign up for a free account to get your API key
  2. Replace "your-api-key" with your actual API key
  3. Update the URL to the webpage you want to scrape
  4. Choose the extraction mode that fits your use case
  5. Run the code and get structured JSON data!

Price Comparison

Compare prices across multiple retailers with intelligent caching and progressive loading for the best UX.

React Component with Progressive Loading

Show Target results in 3-4s, then add eBay results when ready. User sees instant results!

'use client'

import { useState } from 'react'
import { Badge } from '@/components/ui/badge'

export function ProductSearch() {
  const [products, setProducts] = useState([])
  const [loading, setLoading] = useState({ target: false, ebay: false })
  const [query, setQuery] = useState('')

  async function search(searchQuery: string) {
    setProducts([])
    setLoading({ target: true, ebay: true })

    // Fetch Target results (shows in 3-4s)
    fetchRetailer('target', searchQuery).then(results => {
      setProducts(prev => [...prev, ...results])
      setLoading(prev => ({ ...prev, target: false }))
    })

    // Fetch eBay results (shows in 6-7s)
    fetchRetailer('ebay', searchQuery).then(results => {
      setProducts(prev => [...prev, ...results])
      setLoading(prev => ({ ...prev, ebay: false }))
    })
  }

  async function fetchRetailer(retailer: string, searchQuery: string) {
    const response = await fetch('https://api.injectapi.com/api/compare-prices', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.NEXT_PUBLIC_INJECTAPI_KEY!
      },
      body: JSON.stringify({
        product: searchQuery,
        retailers: [retailer],
        format: 'flat'
      })
    })

    const data = await response.json()
    return data.results || []
  }

  return (
    <div>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        onKeyDown={(e) => e.key === 'Enter' && search(query)}
        placeholder="Search products..."
      />

      {/* Product cards */}
      <div className="grid gap-4">
        {products.map((p, i) => (
          <div key={i} className="border p-4 rounded">
            <h3>{p.title}</h3>
            <p className="text-lg font-bold">
              ${p.price} <Badge>{p.retailer}</Badge>
            </p>
            <a href={p.url} target="_blank">View Product</a>
          </div>
        ))}
      </div>

      {/* Loading states */}
      {loading.target && <Badge>Loading Target...</Badge>}
      {loading.ebay && <Badge>Finding more from eBay...</Badge>}
      {!loading.target && !loading.ebay && products.length > 0 && (
        <Badge variant="success">āœ“ All results loaded</Badge>
      )}
    </div>
  )
}

Parallel Requests Pattern

Launch both requests simultaneously for fastest UX. Target results appear in 3-4s, eBay adds 3s later.

async function searchProducts(query) {
  // Start both requests in parallel
  const targetPromise = fetch('https://api.injectapi.com/api/compare-prices', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.INJECTAPI_KEY
    },
    body: JSON.stringify({
      product: query,
      retailers: ['target'],
      format: 'flat'
    })
  }).then(r => r.json())

  const ebayPromise = fetch('https://api.injectapi.com/api/compare-prices', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.INJECTAPI_KEY
    },
    body: JSON.stringify({
      product: query,
      retailers: ['ebay'],
      format: 'flat'
    })
  }).then(r => r.json())

  // Show Target results immediately (3-4s)
  targetPromise.then(data => {
    displayProducts(data.results, 'target')
  })

  // Add eBay results when ready (6-7s total)
  ebayPromise.then(data => {
    addProducts(data.results, 'ebay')
  })
}

Cache-Aware UX

Show cache status to users and adjust UI based on cache freshness.

async function fetchWithCacheAwareness(product) {
  const response = await fetch('https://api.injectapi.com/api/compare-prices', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.INJECTAPI_KEY
    },
    body: JSON.stringify({ product, format: 'flat' })
  })

  const data = await response.json()

  // Check cache headers
  const cacheStatus = response.headers.get('X-Cache')
  const cacheAge = parseInt(response.headers.get('X-Cache-Age') || '0')
  const cacheFresh = response.headers.get('X-Cache-Fresh') === 'true'

  // Or use metadata from response body
  if (data.metadata.from_cache) {
    if (data.metadata.cache_fresh) {
      showBadge('Live prices', 'success')
    } else {
      const ageMinutes = Math.floor(data.metadata.cache_age_seconds / 60)
      showBadge(`Prices from ${ageMinutes}m ago`, 'warning')
    }
  } else {
    showBadge('Live prices', 'success')
  }

  return data.results
}

Product Extraction

Extract product data from e-commerce sites:

const response = await fetch('https://api.injectapi.com/api/extract', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.INJECTAPI_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://www.amazon.com/dp/B08N5WRWNW',
    mode: 'product'
  })
});

const { data } = await response.json();
console.log('Product:', data.title);
console.log('Price:', data.price / 100, data.currency);
console.log('Rating:', data.rating);

Article Extraction

Extract content from blog posts and news articles:

const response = await fetch('https://api.injectapi.com/api/extract', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.INJECTAPI_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://techcrunch.com/article-slug',
    mode: 'article'
  })
});

const { data } = await response.json();
console.log('Title:', data.title);
console.log('Author:', data.author);
console.log('Published:', data.published_date);
console.log('Content:', data.content.substring(0, 200) + '...');

Batch Processing

Process multiple URLs efficiently while respecting rate limits:

async function batchExtract(urls) {
  const results = [];
  const batchSize = 10; // Process 10 URLs at a time

  for (let i = 0; i < urls.length; i += batchSize) {
    const batch = urls.slice(i, i + batchSize);

    const promises = batch.map(url =>
      fetch('https://api.injectapi.com/api/extract', {
        method: 'POST',
        headers: {
          'X-API-Key': process.env.INJECTAPI_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ url, mode: 'product' })
      }).then(r => r.json())
    );

    const batchResults = await Promise.all(promises);
    results.push(...batchResults);

    // Wait 1 second between batches to avoid rate limits
    if (i + batchSize < urls.length) {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }

  return results;
}

// Usage
const urls = [
  'https://amazon.com/product1',
  'https://amazon.com/product2',
  // ... more URLs
];

const products = await batchExtract(urls);
console.log(`Processed ${products.length} products`);

Best Practices

1. Use Environment Variables

Never hardcode your API key. Always use environment variables to keep your credentials secure:

// āœ… Good - Use environment variables
const apiKey = process.env.INJECTAPI_KEY;

// āŒ Bad - Never hardcode API keys!
const apiKey = 'ik_1234567890abcdef';

2. Handle Errors Gracefully

Always check for errors and handle them appropriately:

async function extractData(url) {
  try {
    const response = await fetch('https://api.injectapi.com/api/extract', {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.INJECTAPI_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ url, mode: 'product' })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const { success, data, error } = await response.json();

    if (!success) {
      console.error('API error:', error);
      return null;
    }

    return data;
  } catch (err) {
    console.error('Request failed:', err);
    return null;
  }
}

3. Implement Caching

Cache results to reduce API calls and costs:

const cache = new Map();

async function extractProduct(url) {
  // Check cache first
  if (cache.has(url)) {
    console.log('Cache hit!');
    return cache.get(url);
  }

  // Fetch from API
  const response = await fetch('https://api.injectapi.com/api/extract', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.INJECTAPI_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ url, mode: 'product' })
  });

  const { data } = await response.json();

  // Cache for 1 hour
  cache.set(url, data);
  setTimeout(() => cache.delete(url), 3600000);

  return data;
}

4. Rate Limit Handling

Implement retry logic for rate limits:

async function extractWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('https://api.injectapi.com/api/extract', {
        method: 'POST',
        headers: {
          'X-API-Key': process.env.INJECTAPI_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ url, mode: 'product' })
      });

      if (response.status === 429) {
        // Rate limit exceeded - wait and retry
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        console.log(`Rate limited. Waiting ${retryAfter}s...`);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      return await response.json();
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      // Exponential backoff
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
    }
  }

  throw new Error('Max retries exceeded');
}

Advanced Techniques

Custom Schema Extraction

Extract specific fields using custom instructions:

const response = await fetch('https://api.injectapi.com/api/extract', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.INJECTAPI_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://example.com',
    mode: 'general',
    customSchema: 'Extract the main heading, publication date, and all email addresses'
  })
});

Dynamic Content Waiting

Wait for JavaScript-rendered content to load:

const response = await fetch('https://api.injectapi.com/api/extract', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.INJECTAPI_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://spa-website.com',
    mode: 'product',
    waitFor: 3000 // Wait 3 seconds for content to load
  })
});

Need More Help?