Screenshot API in Elixir with HTTPoison
Elixir applications call the SnapAPI screenshot endpoint using HTTPoison, the popular HTTP client library for Elixir built on hackney. Add {:httpoison, "~> 2.0"} to the dependencies in mix.exs and run mix deps.get. Define a SnapAPI module with a screenshot/2 function that accepts a target URL string and an options keyword list. Build the request URL using URI.encode_query for the query parameters and call HTTPoison.get with the full URL. Pattern match on the {:ok, response} and {:error, reason} return values to handle success and failure cases explicitly. For binary PNG responses, the response.body contains the raw image bytes that can be written to disk with File.write! or processed with the image library. For JSON responses, decode the response body with Jason.decode! to get a map with the image data and page metadata fields.
Elixir's pipe operator makes SnapAPI response processing clean and readable. Chain the HTTPoison.get call with |> then(&HTTPoison.get/1) patterns to transform the URL into the request and then process the response through a series of transformations. A pipeline that takes a URL, encodes the SnapAPI request parameters, calls the API, extracts the base64 image data from the JSON response, decodes it to binary, and writes it to a file can be expressed as a clean sequence of piped function calls that reads naturally from top to bottom. Elixir's with statement provides structured error handling for multi-step pipelines where each step can fail — use with to thread the success values through each step and handle all error cases in a unified else block.
Screenshot API with Oban Background Jobs
Phoenix applications use Oban, the robust job processing library for Elixir, to process screenshot generation asynchronously without blocking web request handlers. Define an Oban worker module ScreenshotWorker with a perform/1 function that pattern matches on the job args map, extracts the target URL, calls the SnapAPI endpoint, stores the result in the database, and broadcasts a PubSub message when complete. Schedule screenshot jobs from Phoenix controllers using ScreenshotWorker.new(%{url: url}) |> Oban.insert(). Oban manages the PostgreSQL-backed job queue, retry logic with configurable backoff, job uniqueness constraints to prevent duplicate screenshot generation for the same URL, and a web-based job monitoring dashboard through Oban Web. The job uniqueness feature is particularly useful for screenshot generation: configure unique_period to prevent scheduling duplicate screenshot jobs for the same URL within a 24-hour window, saving API credits when many users trigger screenshots for the same popular URL.
Oban Pro's Batch plugin enables tracking the progress of bulk screenshot generation jobs where many URLs are processed as a cohesive batch. Insert all screenshot worker jobs with a shared batch ID and use Oban's batch callbacks to fire a completion handler when all jobs in the batch have finished, succeeded, or been discarded. The batch completion callback updates a database record with the batch completion status and triggers downstream processing — generating a ZIP archive of all batch screenshots, sending a notification email, or updating a dashboard widget. Batched screenshot processing with Oban provides the reliability and observability of a production job queue without the operational complexity of running a separate queue service alongside the Phoenix application.
Screenshot API with Phoenix LiveView
Phoenix LiveView components that display screenshot thumbnails use assigns and handle_info callbacks to update the screenshot state in real time as background jobs complete. Mount the LiveView with a screenshot assign initialized to nil and a loading assign set to true. In the mount callback, trigger an asynchronous screenshot job and subscribe to a PubSub topic for the screenshot result. When the Oban worker completes screenshot generation, it broadcasts the screenshot URL to the PubSub topic. The LiveView handle_info callback receives the PubSub broadcast, updates the assigns with the screenshot URL and sets loading to false, and LiveView automatically pushes a DOM patch to the browser updating the screenshot display without a full page reload. This real-time update pattern provides immediate feedback in the browser as screenshots generate, without polling or manual refresh.
Screenshot API Elixir GenServer Cache
An Elixir GenServer provides a simple in-memory screenshot cache that prevents duplicate SnapAPI calls for the same URL within a configurable TTL. Define a ScreenshotCache GenServer with an ETS table for storage, a get/1 function that checks the table for a cached result, and a put/2 function that stores a URL-screenshot pair with an expiry timestamp. Schedule periodic cache cleanup using Process.send_after to remove expired entries without external scheduling infrastructure. Register the GenServer in the application supervision tree so it starts automatically with the application and is restarted if it crashes. The GenServer cache is suitable for single-node Phoenix deployments or development environments where a shared memory cache is acceptable — for multi-node Elixir clusters, use a distributed cache like Cachex with a shared backend or a Redis-backed cache to share screenshot results across all cluster nodes.
Screenshot API Elixir with Tesla HTTP Client
Elixir projects using Tesla as their HTTP client can call the SnapAPI endpoint through a Tesla middleware stack that adds consistent authentication, logging, and retry behavior. Define a SnapAPI Tesla client module with the base URL middleware set to https://snapapi.pics and a query middleware that appends the access_key parameter to all requests. Add Tesla.Middleware.Logger for structured request and response logging and Tesla.Middleware.Retry with configurable retry conditions for 429 and 5xx responses. Tesla's middleware architecture makes it straightforward to add cross-cutting concerns like authentication and retry behavior to all SnapAPI calls without modifying each call site individually. The Tesla mock adapter for testing intercepts HTTP calls and returns pre-configured fixture responses, enabling unit tests that verify screenshot integration behavior without real network calls.
Screenshot API Elixir Distributed Screenshot Cache with Nebulex
Elixir applications deployed as distributed clusters use Nebulex, the multi-tier cache framework for Elixir, to share screenshot cache state across all cluster nodes. Configure Nebulex with a two-tier cache: a local ETS cache for sub-millisecond reads on each node and a distributed Partitioned cache backed by Erlang's distributed data store for cross-node consistency. Define a ScreenshotCache module using the Nebulex.Cache behavior and configure the TTL for screenshot entries to match your freshness requirements. Application code calls ScreenshotCache.get(url) and ScreenshotCache.put(url, screenshot_data) without needing to know whether the result came from the local or distributed tier. The Nebulex distributed cache eliminates redundant SnapAPI calls when the same URL is requested by users connected to different cluster nodes, reducing API usage proportionally to the cluster size.
Screenshot API Phoenix PubSub for Real-Time Screenshot Updates
Phoenix PubSub coordinates screenshot generation status updates across multiple LiveView connections and node boundaries in a distributed Phoenix cluster. When a screenshot generation job completes on any cluster node, the Oban worker broadcasts a Phoenix.PubSub message with the screenshot URL to a topic keyed by the target URL. All LiveView processes subscribed to that topic receive the broadcast and update their assigns to display the newly generated screenshot. This distributed notification pattern ensures that all users viewing a page with a pending screenshot receive the update simultaneously when generation completes, regardless of which cluster node is handling their LiveView connection. The PubSub broadcast approach scales naturally with cluster size because the message delivery is handled by Erlang's distribution layer, not by database polling or custom message routing code.
Elixir Screenshot API with Broadway and GenStage
High-throughput Elixir applications processing large volumes of screenshot requests benefit from Broadway's demand-driven pipeline architecture. Configure a Broadway pipeline with a producer stage that reads screenshot job messages from a queue, a processing stage that calls the SnapAPI HTTP endpoint using Finch as the HTTP client, and a batch processor stage that persists completed screenshots to your storage layer. Broadway's built-in concurrency model handles back-pressure automatically, preventing your Elixir application from overwhelming SnapAPI's rate limits by controlling how many concurrent requests the processing stage maintains. Use Broadway's rate limiting configuration to cap the number of SnapAPI calls per second, respecting the plan-level rate limit while keeping the pipeline throughput as high as possible within those constraints. GenStage producers can push screenshot jobs from multiple sources including Phoenix Channels, Oban background jobs, and direct database polling, making the Broadway pipeline the single integration point for all screenshot generation across the Elixir application.
Elixir Screenshot API Error Recovery with Supervision Trees
Elixir's supervision tree architecture provides natural fault tolerance for screenshot API integrations. Wrap your SnapAPI HTTP client in a supervised GenServer that restarts automatically if it crashes due to network errors or unexpected responses. Use Elixir's with macro to chain the URL validation, SnapAPI call, and result storage steps, returning tagged error tuples at each step that allow the calling code to handle partial failures gracefully. For transient errors like rate limit responses, implement an exponential backoff retry strategy using Process.send_after to reschedule failed jobs rather than blocking the calling process. Phoenix LiveView applications can use Task.async_stream to parallelize multiple screenshot requests while respecting a concurrency limit, providing responsive UI updates as each screenshot completes without blocking the LiveView process on synchronous HTTP calls to SnapAPI.