Python requests with a SOCKS5 proxy

Two things trip people up: a missing dependency, and the difference between socks5 and socks5h.

See plans from $75/mo ♡ Read the docs

Install SOCKS support

pip install "requests[socks]"

Without it requests raises "Missing dependencies for SOCKS support".

Basic request with authentication

import requests

proxy = 'socks5h://USER:PASS@HOST:PORT'
proxies = {'http': proxy, 'https': proxy}

r = requests.get('https://api.ipify.org', proxies=proxies, timeout=30)
print(r.text)

socks5 or socks5h

With socks5 your computer resolves the hostname and only the connection goes through the proxy. With socks5h the proxy resolves it. Use socks5h so DNS lookups do not leak from your own network and the site is resolved from the proxy's location.

Reuse a session

s = requests.Session()
s.proxies.update(proxies)
for url in urls:
    print(s.get(url, timeout=30).status_code)

Common errors

Questions

Does httpx or aiohttp work the same way?

httpx needs its own extra (httpx[socks]); aiohttp needs a connector package such as aiohttp-socks.

Can I use the HTTP port instead?

Yes. Replace the scheme with http:// and no extra package is needed.

Related guides

Ready for your own dedicated private mobile proxy? 🎀

Real AT&T, Verizon and T-Mobile SIMs · unlimited data · one-tap IP rotation · delivered by email or Telegram.