BuyProxy logo
Log inSign up

SDKs

Rust SDK

The official Rust library for BuyProxy: generate residential, mobile, ISP and datacenter proxies, check bandwidth, buy more by card or crypto, and run a reseller business. Rust 1.75+, async on tokio and reqwest with rustls (no OpenSSL). Client is cheap to clone and safe to share between tasks.

  • Async, Clone-cheap Client, safe to share between tasks

  • Builder-style GenerateParams and a single typed Error with is_*() helpers

  • Proxy::to_reqwest() plugs straight into reqwest

  • Automatic retries with back-off for rate limits and transient errors

Source, issues and releases: github.com/DishantSinghDev2/buyproxy-rust

Installation

bash
cargo add buyproxy tokio --features tokio/full

Rust 1.75+. TLS via rustls โ€” no OpenSSL needed.

Authentication

Create an API key under Dashboard โ†’ API keys โ€” personal keys start bp_key_, reseller keys bp_live_. The SDK reads BUYPROXY_API_KEY from the environment automatically; you can also pass the key explicitly. A missing key fails immediately with an authentication error, without a network call.

rust
// 1. Environment variable (recommended)
let client = Client::new();

// 2. Explicit key, e.g. from a secrets manager
let client = Client::builder().api_key(secret).build();

// 3. Which kind of key is it?
println!("{:?}", client.key_kind()); // Some("personal") | Some("reseller") | None
Never put an API key in client-side code, a mobile app, a public repository or a log line. Revoke a leaked key from the dashboard and create a new one.

Quick start

rust
use buyproxy::{Client, GenerateParams};

#[tokio::main]
async fn main() -> buyproxy::Result<()> {
    let client = Client::new(); // reads BUYPROXY_API_KEY โ€” or Client::builder().api_key("bp_key_โ€ฆ").build()

    let plans = client.plans().list().await?;
    let out = client
        .plans()
        .generate(&plans[0].id, &GenerateParams::new().country("US").city("Austin").count(5))
        .await?;

    println!("{}", out.proxies[0].url()); // http://user-country-us-city-austin:pass@gw.buyproxy.org:6969
    Ok(())
}

Add .sticky_minutes(10) to keep the same IP for ten minutes, or .protocol(Protocol::Socks5) for SOCKS5.

Generating proxies

Generation is free and instant โ€” bandwidth is only consumed when traffic flows through a proxy. Every parameter is optional; omit one and the API's default applies. (Names follow each language's conventions, e.g. stickyMinutes / sticky_minutes / StickyMinutes.)

ParameterTypeWhat it does
protocol"http" \"socks5"Proxy protocol. Default http (which also carries HTTPS). Check plan.generate.protocols for what a product supports
countinteger 1โ€“1000How many proxy lines to return. Default 1
countryISO 3166-1 alpha-2e.g. US, DE, JP. Omit for a worldwide IP
statestringState or region, where the product supports it
citystringCity, where the product supports it
ispstringNetwork / carrier, where the product supports it
stickyMinutesintegerKeep the same IP for this many minutes. Omit for a fresh IP on every request. The maximum is plan.generate.maxStickyMinutes; 0 there means the product has no sticky sessions

Each returned line is username:password@host:port with your targeting encoded in the username. Lines are on-demand and not persistent โ€” generate fresh ones when you need them instead of storing them, because credentials can rotate when the pool moves.

rust
// Country, state and city โ€” what a plan supports is in plan.generate.targeting
client.plans().generate(&plan.id, &GenerateParams::new().country("US").state("California").city("Los Angeles")).await?;

// Sticky session: keep one IP for 30 minutes (max is plan.generate.max_sticky_minutes)
client.plans().generate(&plan.id, &GenerateParams::new().country("DE").sticky_minutes(30)).await?;

// SOCKS5 instead of HTTP
client.plans().generate(&plan.id, &GenerateParams::new().protocol(Protocol::Socks5).count(10)).await?;

// Bulk: up to 1000 lines per call
let out = client.plans().generate(&plan.id, &GenerateParams::new().count(1000)).await?;
std::fs::write("proxies.txt", out.lines.join("\n"))?;

Every top-up and allocation call takes a product key. Live prices come from the catalog call, so you never hard-code a rate.

KeyProductMin orderBest for
residentialCore Residential1 GBEveryday rotating residential IPs with country targeting
premiumPremium Residential2 GBCity-level targeting, sticky sessions and priority routing
ispISP Rotating1 GBDatacenter speed with ISP-grade trust
mobileMobile Proxies1 GBReal carrier IPs for mobile-only targets
ipv4Datacenter IPv41 GBFast, cheap per-GB datacenter traffic
ipv6IPv6 Proxies1 GBHuge address diversity at the lowest per-GB rate

Pay-as-you-go top-ups of 100 GB or more include a 10% volume bonus, and a single order is capped at 10,000 GB.

Using the proxies with your stack

Each generated proxy is a small object (host, port, username, password, protocol) with helpers that return exactly what common clients expect, so you never hand-build a proxy URL or worry about percent-encoding special characters in a password.

reqwest

rust
let http = reqwest::Client::builder().proxy(out.proxies[0].to_reqwest()?).build()?;
println!("{}", http.get("https://api.ipify.org").send().await?.text().await?);

curl & shell

rust
println!("{}", out.proxies[0].curl());   // ready-to-run curl command
println!("{:?}", out.proxies[0].env());  // HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, โ€ฆ

Account, balances & history

Read-only calls for building dashboards, alerts and pre-flight checks. balances is the one to watch: it shows spendable GB per product, including GB from a payment that's still being added (pending).

rust
let catalog = client.products().await?;            // product keys & live prices โ€” no API key needed
let account = client.account().await?;              // email, plan, lifetime GB
let balances = client.balances().await?;            // spendable GB per product (+ GB still arriving)
let plans = client.plans().list().await?;           // plan ids and what each can generate
let history = client.transactions().list(Some(20)).await?;

Buying bandwidth

  1. Call the top-up method โ€” it returns a hosted payment URL and a transaction id. Card payments are processed by Stripe Checkout; crypto by an invoice page.
  2. Send your user (or yourself) to that URL to pay.
  3. Poll the transaction (or use the SDK's wait helper) until status is succeeded or failed. Crypto payments are checked live on every poll, so they settle even if a webhook is delayed.
  4. The GB shows up under balances within seconds โ€” pendingGb while it's arriving, activeGb once it's live.

Plans are subscriptions billed monthly or yearly by card (crypto only covers pay-as-you-go top-ups). If the account already has a subscription, the call returns the subscription settings page as the URL and a null transaction id โ€” switching plans is prorated there, and you can't accidentally subscribe twice.

rust
use buyproxy::{BillingInterval, CardCheckoutParams, PaidPlan, ProductKey};

// Buy 10 GB of Core Residential by card โ€” open pay_url in a browser
let checkout = client.topup().card(&CardCheckoutParams::Topup { product_key: ProductKey::Residential, gb: 10 }).await?;
println!("{}", checkout.pay_url);

// Or subscribe to a plan (monthly or yearly)
client.topup().card(&CardCheckoutParams::Plan { plan: PaidPlan::Pro, interval: Some(BillingInterval::Year) }).await?;

// Crypto (pay-as-you-go top-ups only)
client.topup().crypto(ProductKey::Residential, 50).await?;

// Wait for the payment to settle โ€” GB appears on client.balances() right after
let tx = client.transactions().wait(&checkout.transaction_id.unwrap(), Duration::from_secs(3), Duration::from_secs(600)).await?;

Card payments are processed by Stripe; crypto top-ups are pay-as-you-go only. Subscriptions can be managed or cancelled from Dashboard โ†’ Billing.

Reseller API

The reseller API lets you build a proxy product on top of BuyProxy. The flow is always the same:

  1. Fund your pool โ€” buy GB per product into your reseller pool by card or crypto. Pool GB is priced like a normal top-up (including the volume bonus), fixed at purchase time.
  2. Create a customer โ€” an isolated sub-account with its own credentials and no bandwidth. Store the returned username.
  3. Allocate โ€” move whole GB of one product from your pool onto that customer, with an idempotency key. The first allocation of a product creates the plan; later ones add to it.
  4. Generate โ€” produce proxy lines for the customer from their plan id (found on the customer record), with all the usual targeting options.
  5. Monitor โ€” read the customer's usage (remaining, used, total per plan, plus any GB still arriving) to bill or alert.
  6. Suspend / reactivate โ€” a suspended customer can't generate new lines (403). Lines already handed out may keep working until they rotate, so stop distributing them at the same time. You can also rename a customer.

Allocated GB can't be moved back to the pool, so allocate what a customer has paid for.

rust
let reseller = Client::builder().api_key("bp_live_โ€ฆ").build();

reseller.reseller().pool().topup_card(ProductKey::Residential, 500).await?;       // buy into your pool
let customer = reseller.reseller().customers().create("Acme Inc").await?;         // isolated sub-account

reseller.reseller().customers().allocate(&customer.username, &AllocateParams {
    product_key: ProductKey::Residential, gb: 20, idempotency_key: Some("order-1042".into()), // safe to retry
}).await?;

let detail = reseller.reseller().customers().get(&customer.username).await?;
let out = reseller.reseller().customers()
    .generate(&customer.username, &detail.plans[0].plan.id, &GenerateParams::new().country("DE")).await?;

reseller.reseller().customers().update(&customer.username, None, Some(CustomerStatus::Suspended)).await?;

Allocating bandwidth to a customer moves real GB, so it accepts an idempotency key. Send the same key twice and the second call moves nothing and returns alreadyApplied: true with the same result โ€” safe to retry after a timeout or crash.

Use a value you can derive again from your own data (an order id, an invoice number), not a random value created per attempt. Keys are scoped to your account and may be up to 200 characters.

Errors & retries

Every non-success response becomes a typed error carrying the HTTP status and the API's own message, so you can branch on the failure instead of parsing strings.

HTTPCheck withMeaning
400err.is_validation()A parameter was missing or invalid
401err.is_authentication()Missing or invalid API key (Error::MissingApiKey is returned locally when none is set)
402err.is_insufficient_bandwidth()Empty reseller pool, or a plan with no GB left
403err.is_forbidden()Suspended account/customer, or the plan doesn't include this endpoint
404err.is_not_found()Plan, customer or transaction not found on this account
429err.is_rate_limited()Over 60 requests/minute โ€” Error::Api { retry_after, .. }
5xxerr.is_server_error()BuyProxy or an upstream provider is unavailable
โ€”Error::ConnectionNo response (DNS, reset, timeout, offline)
rust
match client.plans().generate(&plan_id, &GenerateParams::new()).await {
    Ok(out) => println!("{} proxies", out.proxies.len()),
    Err(e) if e.is_insufficient_bandwidth() => println!("Out of GB โ€” top up first"),
    Err(e) if e.is_rate_limited() => println!("Slow down: {e}"),
    Err(e) if e.is_authentication() => println!("Check your API key"),
    Err(e) => return Err(e),
}

Every SDK retries for you, with the same rules:

  • Rate limits (`429`) are always retried, waiting for the Retry-After the API sends (capped at 30 s) or an exponential back-off with jitter.
  • Reads (GET) are also retried on 502/503/504 and on network failures.
  • Writes are not retried on server errors โ€” a repeated checkout or allocation must never double-charge โ€” unless you attach an idempotency key (see below), which makes the retry provably safe.
  • The default is 2 retries; set it to 0 to turn retries off. After the last attempt you get the typed error.

The API allows 60 requests per minute per key. Batch with count (up to 1000 lines per call) rather than looping over single-proxy calls.

Configuration

rust
let client = Client::builder()
    .api_key("bp_key_โ€ฆ")                         // default: $BUYPROXY_API_KEY
    .base_url("https://www.buyproxy.org")
    .timeout(Duration::from_secs(30))
    .max_retries(2)                               // 429s always; 5xx only for safe requests
    .http_client(my_reqwest_client)               // bring your own reqwest::Client
    .build();

Concurrency

rust
// Client is Clone + Send + Sync โ€” run calls concurrently (mind the 60 requests/minute limit)
let (a, b) = tokio::try_join!(
    client.plans().generate(&plan_a.id, &GenerateParams::new().count(10)),
    client.plans().generate(&plan_b.id, &GenerateParams::new().count(10)),
)?;

Testing your code

You don't need a real account or network to unit-test code that uses the SDK โ€” inject a fake transport. This is how the SDK's own test suite works.

rust
use wiremock::{matchers::path, Mock, MockServer, ResponseTemplate};

let server = MockServer::start().await;
Mock::given(path("/v1/plans/plan_1/generate"))
    .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "lines": ["u:p@gw.buyproxy.org:6969"] })))
    .mount(&server)
    .await;

let client = Client::builder().api_key("bp_key_test").base_url(server.uri()).build();
let out = client.plans().generate("plan_1", &GenerateParams::new()).await?;
assert_eq!(out.proxies[0].host, "gw.buyproxy.org");

API reference

Every method maps one-to-one onto a documented REST endpoint.

CapabilityCall
Catalog & pricesclient.products()
Accountclient.account()
Spendable GB per productclient.balances()
Plansclient.plans().list()
Generate proxiesclient.plans().generate(id, &params)
Card checkoutclient.topup().card(&params)
Crypto checkoutclient.topup().crypto(product, gb)
Paymentsclient.transactions().list/get/wait
Create an accountclient.signup() ยท .verify_otp() ยท .resend_otp()
Reseller summaryclient.reseller().me()
Customersclient.reseller().customers().list/create/get/update/usage/allocate/generate
Reseller poolclient.reseller().pool().get/topup_card/topup_crypto

Notes

  • A single Error enum covers everything: Api { status, message, body, retry_after }, MissingApiKey, Connection, Decode and InvalidProxyLine.

  • ProductKey has an Other variant so a product added after your SDK version still deserialises.

  • Proxy::to_reqwest() plugs straight into reqwest::Client::builder().proxy(โ€ฆ).

Developing the SDK

bash
cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test

Was this page helpful?