DEV Community

Revo
Revo

Posted on

How to Rotate IPs in Python with a 4G Mobile Proxy API (2025 Guide)

Web scraping at scale always comes down to one problem: getting blocked. Datacenter IPs get flagged instantly. Residential proxies trigger CAPTCHAs constantly. The solution that actually works in 2025 is 4G mobile proxies with API-controlled rotation.

This tutorial shows you how to rotate IPs on demand using the https://iaproxy.com mobile proxy API.

Why Mobile Proxies?

4G carrier IPs (Viettel, VNPT, FPT in Vietnam — or US mobile carriers) are classified as legitimate mobile traffic. Websites are far less likely to block them because that would mean blocking real smartphone users. Vietnam carrier IPs in particular carry very clean abuse histories — lower CAPTCHA rates, better bypass on Instagram, TikTok, Cloudflare-protected sites.

Setup

You need:

  • An https://iaproxy.com account with at least one active proxy
  • Your proxy credentials (host, port, username, password)
  • Your package API key — find it in the dashboard under My Proxies

Basic Rotation with requests

import requests
import time

PROXY_HOST = "your-proxy-host"
PROXY_PORT = 8080
PROXY_USER = "your-username"
PROXY_PASS = "your-password"
API_KEY    = "your-package-api-key"

def get_proxy():
    auth = f"{PROXY_USER}:{PROXY_PASS}"
    addr = f"{PROXY_HOST}:{PROXY_PORT}"
    return {
        "http":  f"http://{auth}@{addr}",
        "https": f"http://{auth}@{addr}",
    }

def rotate_ip(api_key: str) -> bool:
    """Rotate IP via iaProxy API. Returns True on success."""
    url = f"https://iaproxy.com/api/change_ip.php?package_api_key={api_key}"
    try:
        r = requests.get(url, timeout=10)
        data = r.json()
        if data.get("Status") == "Success":
            print("IP rotated successfully")
            return True
        else:
            print(f"Rotation result: {data.get('Message')}")
            return False
    except Exception as e:
        print(f"Rotation error: {e}")
        return False

# Example: scrape 100 URLs, rotate every 30 requests
urls = [f"https://example.com/page/{i}" for i in range(100)]

for i, url in enumerate(urls):
    if i > 0 and i % 30 == 0:
        rotate_ip(API_KEY)
        time.sleep(2)  # let new IP stabilize

    try:
        response = requests.get(
            url,
            proxies=get_proxy(),
            headers={"User-Agent": "Mozilla/5.0 (Linux; Android 13; Pixel 7)"},
            timeout=15
        )
        print(f"[{i}] Status: {response.status_code}")
    except Exception as e:
        print(f"[{i}] Error: {e}")

    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

Scrapy Integration

# middlewares.py
import requests, time

class MobileProxyMiddleware:
    API_KEY = "your-package-api-key"
    PROXY   = "http://user:pass@proxy-host:8080"
    COUNT   = 0

    def process_request(self, request, spider):
        self.COUNT += 1
        if self.COUNT % 40 == 0:
            self._rotate()
        request.meta["proxy"] = self.PROXY

    def _rotate(self):
        r = requests.get(
            f"https://iaproxy.com/api/change_ip.php?package_api_key={self.API_KEY}",
            timeout=8
        )
        if r.json().get("Status") == "Success":
            time.sleep(2)
Enter fullscreen mode Exit fullscreen mode

API Response Reference

// Success
{"Status": "Success", "Message": "Success"}

// Too soon (respect your plan interval)
{"Status": "Error", "Message": "Please wait 120 seconds"}

// Missing key
{"Status": "Error", "Message": "Missing package_api_key"}
Enter fullscreen mode Exit fullscreen mode

Tips

  • Always check Status field, not the HTTP status code (always 200)
  • Wait 2–3 seconds after rotation before the next request
  • Match your User-Agent to a mobile browser — it pairs naturally with a mobile carrier IP
  • For plans with 2-min rotation, rotation_interval = 120

Full API docs: https://iaproxy.com/api/docs
Try it free: https://t.me/iaproxysupport

Top comments (0)