screenshotfreeapi 1.0.0

Official Rust client for ScreenshotFreeAPI — Screenshot-as-a-Service
Documentation
use std::sync::Arc;

use crate::error::Result;
use crate::http::HttpClient;
use crate::resources::{
    auth::AuthResource,
    billing::BillingResource,
    integrations::IntegrationsResource,
    jobs::JobsResource,
    monitors::MonitorsResource,
    screenshots::{wait_for_job, ScreenshotsResource, WaitOptions},
    workspaces::WorkspacesResource,
};
use crate::types::{HealthResponse, JobResult, WebScreenshotOptions};

/// The main entry point for the ScreenshotFreeAPI Rust client.
///
/// Construct with [`ScreenshotFreeAPIClient::new`] and access endpoints through the
/// resource fields:
///
/// ```rust,no_run
/// use screenshotfreeapi::ScreenshotFreeAPIClient;
///
/// #[tokio::main]
/// async fn main() -> screenshotfreeapi::Result<()> {
///     let client = ScreenshotFreeAPIClient::new("sfa_your_api_key");
///
///     // Quick one-liner capture
///     let result = client.capture("https://stripe.com").await?;
///     println!("{}", result.screenshots[0].url);
///     Ok(())
/// }
/// ```
///
/// # Resources
///
/// | Field | Endpoints |
/// |---|---|
/// | `auth` | `/auth/register`, `/auth/token`, `/auth/refresh` |
/// | `screenshots` | `/screenshots/web`, `/screenshots/mobile`, `/screenshots/html` |
/// | `jobs` | `/jobs/:id/status`, `/jobs/:id/result` |
/// | `billing` | `/billing/*` |
/// | `workspaces` | `/workspaces/*` |
/// | `monitors` | `/monitors/app/*` |
/// | `integrations` | `/integrations/zapier/*` |
#[derive(Clone)]
pub struct ScreenshotFreeAPIClient {
    http: Arc<HttpClient>,

    /// Auth endpoints — register, token, refresh.
    pub auth: AuthResource,

    /// Screenshot capture endpoints.
    pub screenshots: ScreenshotsResource,

    /// Job status polling and result fetching.
    pub jobs: JobsResource,

    /// Billing plans, usage, upgrades, and cancellation.
    pub billing: BillingResource,

    /// Team workspace management.
    pub workspaces: WorkspacesResource,

    /// Scheduled app monitors.
    pub monitors: MonitorsResource,

    /// Zapier REST Hook integrations.
    pub integrations: IntegrationsResource,
}

impl ScreenshotFreeAPIClient {
    /// Create a client using the production base URL (`https://api.screenshotfreeapi.com`).
    ///
    /// ```rust
    /// use screenshotfreeapi::ScreenshotFreeAPIClient;
    /// let client = ScreenshotFreeAPIClient::new("sfa_your_api_key");
    /// ```
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::with_base_url(api_key, "https://api.screenshotfreeapi.com")
    }

    /// Create a client with a custom base URL.  Useful for testing against a
    /// local development server or a staging environment.
    ///
    /// ```rust
    /// use screenshotfreeapi::ScreenshotFreeAPIClient;
    /// let client = ScreenshotFreeAPIClient::with_base_url("sfa_test_key", "http://localhost:3000");
    /// ```
    pub fn with_base_url(
        api_key: impl Into<String>,
        base_url: impl Into<String>,
    ) -> Self {
        let http = Arc::new(HttpClient::new(api_key.into(), base_url.into()));

        Self {
            auth: AuthResource { http: Arc::clone(&http) },
            screenshots: ScreenshotsResource { http: Arc::clone(&http) },
            jobs: JobsResource { http: Arc::clone(&http) },
            billing: BillingResource { http: Arc::clone(&http) },
            workspaces: WorkspacesResource { http: Arc::clone(&http) },
            monitors: MonitorsResource { http: Arc::clone(&http) },
            integrations: IntegrationsResource { http: Arc::clone(&http) },
            http,
        }
    }

    // -----------------------------------------------------------------------
    // Convenience
    // -----------------------------------------------------------------------

    /// One-liner: enqueue a web screenshot for `url` and wait for it to finish.
    ///
    /// Uses [`WaitOptions::default`] (2-second polling interval, 120-second timeout).
    ///
    /// ```rust,no_run
    /// use screenshotfreeapi::ScreenshotFreeAPIClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> screenshotfreeapi::Result<()> {
    ///     let client = ScreenshotFreeAPIClient::new("sfa_your_api_key");
    ///     let result = client.capture("https://github.com").await?;
    ///     println!("Screenshot URL: {}", result.screenshots[0].url);
    ///     Ok(())
    /// }
    /// ```
    pub async fn capture(&self, url: &str) -> Result<JobResult> {
        let enq = self
            .screenshots
            .capture_web(WebScreenshotOptions {
                url: url.to_string(),
                ..Default::default()
            })
            .await?;
        wait_for_job(&self.http, &enq.job_id, WaitOptions::default()).await
    }

    /// Check the API health.
    ///
    /// Corresponds to `GET /health`. Does not require authentication.
    pub async fn health(&self) -> Result<HealthResponse> {
        self.http.get("/health", None).await
    }
}