### Queue and Run Single Request Source: https://context7.com/alphapapa/plz.el/llms.txt Adds a single GET request to a queue and then executes the queued requests. The `plz-run` function initiates the processing of requests managed by the queue. ```elisp ;; Queue and run a single request (plz-run (plz-queue my-queue 'get "https://httpbin.org/get?foo=0" :then (lambda (body) (message "Got: %s" (substring body 0 30))))) ``` -------------------------------- ### Async File Download Source: https://context7.com/alphapapa/plz.el/llms.txt Initiates an asynchronous GET request to download a file and save it to a specified path, then opens the downloaded file. This is useful for retrieving resources like images or documents. ```elisp ;; Async file download (plz 'get "https://httpbin.org/image/jpeg" :as '(file "~/Downloads/image.jpg") :then (lambda (filename) (find-file filename))) ``` -------------------------------- ### Synchronous Requests Source: https://context7.com/alphapapa/plz.el/llms.txt Synchronous requests using `plz` will block execution until a response is received or an error occurs. The `:then 'sync` option (which is the default) ensures the function waits for the result. This section provides examples of simple GET requests, requests with timeouts, JSON parsing, and other HTTP methods like PUT, HEAD, and PATCH. ```APIDOC ## GET /users/{userId} ### Description Retrieves the details of a specific user identified by their ID. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (integer) - Required - The unique identifier of the user to retrieve. #### Query Parameters - **includeDetails** (boolean) - Optional - If true, includes additional details about the user. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **details** (object) - Optional - Additional user information if `includeDetails` is true. #### Response Example ```json { "id": 456, "username": "janedoe", "email": "jane.doe@example.com", "details": { "firstName": "Jane", "lastName": "Doe" } } ``` ``` -------------------------------- ### Asynchronous Requests Source: https://context7.com/alphapapa/plz.el/llms.txt Make non-blocking HTTP requests using `plz` and handle responses with callbacks. Supports GET, POST, JSON, file downloads, and concurrent requests. ```APIDOC ## Asynchronous Requests Non-blocking requests that execute callbacks when complete. Essential for responsive Emacs applications that need to make HTTP requests without freezing. ### GET Request with Callback Performs a GET request and processes the response body in a callback. ### Method GET ### Endpoint `https://httpbin.org/get` ### Parameters #### Query Parameters - **`then`** (function) - Required - Callback function to execute upon successful completion. Receives the response body as an argument. ### Request Example ```elisp ;; Basic async request with callback (plz 'get "https://httpbin.org/get" :then (lambda (body) (message "Received: %s" (substring body 0 50)))) ``` ### Response #### Success Response (200) - **body** (string) - The response body from the server. ### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Received: { ;; "args": {}, ;; "headers": { ;; "Accept": "*/*", ;; "Connection": "close", ;; "Host": "httpbin.org", ;; "User-Agent": "Emacs-plz/29.1" ;; }, ;; "origin": "", ;; "url": "https://httpbin.org/get" ;; } ``` --- ### Async GET Request with Error Handling Handles both successful responses and errors (HTTP or curl errors) using `:then`, `:else`, and `:finally` callbacks. ### Method GET ### Endpoint `https://httpbin.org/status/500` ### Parameters #### Query Parameters - **`then`** (function) - Optional - Callback for success. - **`else`** (function) - Optional - Callback for errors. Receives the error object. - **`finally`** (function) - Optional - Callback executed regardless of success or failure. ### Request Example ```elisp ;; Async with error handling (plz 'get "https://httpbin.org/status/500" :then (lambda (body) (message "Success!")) :else (lambda (err) (let ((response (plz-error-response err))) (when response (message "HTTP %d error" (plz-response-status response))))) :finally (lambda () (message "Cleanup complete"))) ``` ### Response #### Error Response (500) - **err** (object) - An error object containing details about the failure. #### Response Example ```elisp ;; Example output in the *Messages* buffer for a 500 error: ;; HTTP 500 error ;; Cleanup complete ``` --- ### Async POST Request with JSON Body Sends a POST request with a JSON payload and custom headers, processing a JSON response. ### Method POST ### Endpoint `https://httpbin.org/post` ### Parameters #### Query Parameters - **`headers`** (list) - Optional - A list of cons cells representing request headers (e.g., `'(("Content-Type" . "application/json"))`). - **`body`** (string) - Required - The request body, typically JSON-encoded. - **`as`** (symbol or list) - Optional - Specifies how to process the response. `#'json-read` parses the response as JSON. - **`then`** (function) - Optional - Callback for success. ### Request Example ```elisp ;; Async POST with JSON (plz 'post "https://httpbin.org/post" :headers '(("Content-Type" . "application/json") ("Authorization" . "Bearer token123")) :body (json-encode '(("action" . "create") ("data" . [1 2 3]))) :as #'json-read :then (lambda (response) (message "Created with data: %s" (alist-get 'data response)))) ``` ### Response #### Success Response (200) - **response** (hash-table or alist) - The parsed JSON response body. #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Created with data: (1 2 3) ``` --- ### Async File Download Downloads a file from a URL and saves it to a specified local path. ### Method GET ### Endpoint `https://httpbin.org/image/jpeg` ### Parameters #### Query Parameters - **`as`** (list) - Required - Specifies the output format and path. Example: `'(file "~/Downloads/image.jpg")`. - **`then`** (function) - Optional - Callback function executed upon successful download, receiving the saved filename. ### Request Example ```elisp ;; Async file download (plz 'get "https://httpbin.org/image/jpeg" :as '(file "~/Downloads/image.jpg") :then (lambda (filename) (find-file filename))) ``` ### Response #### Success Response (200) - **filename** (string) - The local path where the file was saved. #### Response Example ```elisp ;; If successful, opens the downloaded image file in Emacs. ;; "~/Downloads/image.jpg" is opened. ``` --- ### Multiple Concurrent Requests Initiates multiple asynchronous GET requests concurrently. Each request returns immediately, and callbacks handle individual responses. ### Method GET ### Endpoint `https://httpbin.org/get?id=` ### Parameters #### Query Parameters - **`as`** (symbol or list) - Optional - Specifies response processing (e.g., `#'json-read`). - **`then`** (function) - Optional - Callback for each successful response. ### Request Example ```elisp ;; Multiple concurrent requests (each returns immediately) (dolist (id '(1 2 3 4 5)) (plz 'get (format "https://httpbin.org/get?id=%d" id) :as #'json-read :then (lambda (data) (message "Got response for request")))) ``` ### Response #### Success Response (200) - **data** (any) - The processed response data (e.g., parsed JSON). #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Got response for request ;; Got response for request ;; ... (for each request) ``` ``` -------------------------------- ### Queue HTTP Requests with plz.el Source: https://github.com/alphapapa/plz.el/blob/master/README.org Demonstrates how to use plz.el to queue and run multiple HTTP GET requests. It initializes a queue with a concurrency limit and processes a list of URLs, logging the response body for each. The queue is configured with a finalizer function that is called when the queue becomes empty. ```elisp (defvar my-queue (make-plz-queue :limit 2)) (plz-run (plz-queue my-queue 'get "https://httpbin.org/get?foo=0" :then (lambda (body) (message "%s" body)))) ``` ```elisp (let ((queue (make-plz-queue :limit 2 :finally (lambda () (message "Queue empty.")))) (urls '("https://httpbin.org/get?foo=0" "https://httpbin.org/get?foo=1"))) (plz-run (dolist (url urls queue) (plz-queue queue 'get url :then (lambda (body) (message "%s" body)))))) ``` -------------------------------- ### Async Request with Error Handling Source: https://context7.com/alphapapa/plz.el/llms.txt Demonstrates asynchronous GET request with explicit handling for success (:then), failure (:else), and completion (:finally) callbacks. This pattern is essential for robust network operations. ```elisp ;; Async with error handling (plz 'get "https://httpbin.org/status/500" :then (lambda (body) (message "Success!")) :else (lambda (err) (let ((response (plz-error-response err))) (when response (message "HTTP %d error" (plz-response-status response))))) :finally (lambda () (message "Cleanup complete"))) ``` -------------------------------- ### Basic Async Request with Callback Source: https://context7.com/alphapapa/plz.el/llms.txt Performs a basic asynchronous GET request and executes a callback function with the response body. Useful for simple data retrieval without blocking the Emacs event loop. ```elisp ;; Basic async request with callback (plz 'get "https://httpbin.org/get" :then (lambda (body) (message "Received: %s" (substring body 0 50)))) ``` -------------------------------- ### Concurrent Async Requests Source: https://context7.com/alphapapa/plz.el/llms.txt Executes multiple asynchronous GET requests concurrently using a loop. Each request is initiated without blocking, allowing for parallel fetching of data. ```elisp ;; Multiple concurrent requests (each returns immediately) (dolist (id '(1 2 3 4 5)) (plz 'get (format "https://httpbin.org/get?id=%d" id) :as #'json-read :then (lambda (data) (message "Got response for request")))) ``` -------------------------------- ### Synchronous GET Request (Emacs Lisp) Source: https://github.com/alphapapa/plz.el/blob/master/README.org Performs a synchronous HTTP GET request to the specified URL and returns the response body as a decoded string. This is useful for fetching simple text or JSON data. ```elisp (plz 'get "https://httpbin.org/user-agent") ``` -------------------------------- ### Core Function: plz Source: https://context7.com/alphapapa/plz.el/llms.txt The main public function `plz` is used to make HTTP requests. It supports various methods (GET, POST, PUT, PATCH, DELETE, HEAD) and can execute requests synchronously or asynchronously. It also allows for custom headers, request bodies, and specifies how the response should be handled (e.g., as a string, parsed JSON, binary data, or a full response object). Callbacks can be provided for handling successful responses (`:then`) and errors (`:else`). ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users in the system. It requires user details in the request body and returns the newly created user object upon success. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of results to return. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. - **createdAt** (string) - The timestamp when the user was created. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Synchronous GET Request with JSON Parsing (Emacs Lisp) Source: https://github.com/alphapapa/plz.el/blob/master/README.org Executes a synchronous HTTP GET request and parses the JSON response body into an Emacs Lisp alist. This function requires the 'json-read' function for parsing. ```elisp (plz 'get "https://httpbin.org/get" :as #'json-read) ``` -------------------------------- ### Making HTTP Requests with plz Source: https://context7.com/alphapapa/plz.el/llms.txt The core 'plz' function for making HTTP requests. It supports multiple methods (GET, POST, PUT, PATCH, DELETE, HEAD) and can execute synchronously or asynchronously. It allows customization of headers, request bodies, and response formats, including automatic parsing of JSON and binary data, file downloads/uploads, and detailed response structures. ```elisp ;; Synchronous GET request - returns response body as string (plz 'get "https://httpbin.org/get") ;; => "{\n \"args\": {}, \n \"headers\": {...}\n}\n" ;; GET with JSON parsing - returns parsed alist (plz 'get "https://httpbin.org/get" :as #'json-read) ;; => ((args) (headers (Accept . "*/*") (Host . "httpbin.org")) (url . "https://httpbin.org/get")) ;; Asynchronous GET with callback (plz 'get "https://httpbin.org/get" :as #'json-read :then (lambda (alist) (message "URL: %s" (alist-get 'url alist)))) ;; Prints: URL: https://httpbin.org/get ;; POST with JSON body (plz 'post "https://httpbin.org/post" :headers '(("Content-Type" . "application/json")) :body (json-encode '(("key" . "value"))) :as #'json-read :then (lambda (alist) (message "Result: %s" (alist-get 'data alist)))) ;; Prints: Result: {"key":"value"} ;; Download binary data (let ((jpeg-data (plz 'get "https://httpbin.org/image/jpeg" :as 'binary))) (create-image jpeg-data nil 'data)) ;; => (image :type jpeg :data "...") ;; Download to file (plz 'get "https://httpbin.org/image/png" :as '(file "/tmp/downloaded-image.png") :then (lambda (filename) (message "Saved to: %s" filename))) ;; Upload file from disk (plz 'post "https://httpbin.org/post" :body '(file "/path/to/upload.txt") :then (lambda (body) (message "Upload complete"))) ;; Full response structure with headers and status (plz 'get "https://httpbin.org/get" :as 'response) ;; => #s(plz-response 1.1 200 ((content-type . "application/json") ...) "...") ;; Error handling with :else callback (plz 'get "https://httpbin.org/status/404" :then (lambda (body) (message "Success: %s" body)) :else (lambda (err) (message "Error: %s" (plz-error-message err))) :finally (lambda () (message "Request finished"))) ``` -------------------------------- ### Request Queue Initialization Source: https://context7.com/alphapapa/plz.el/llms.txt Creates a request queue with a specified concurrency limit. This queue manages outgoing HTTP requests, ensuring that only a certain number execute simultaneously. ```elisp ;; Create a queue with concurrency limit of 2 (defvar my-queue (make-plz-queue :limit 2)) ``` -------------------------------- ### Configure plz.el Default Settings and Per-Request Options in Elisp Source: https://context7.com/alphapapa/plz.el/llms.txt Illustrates how to customize the default behavior of the plz library by setting global variables and providing per-request arguments. This includes configuring the curl program path, default arguments, timeouts, and request-specific options like disabling query on process kill or sending binary data. ```elisp ;; Set default curl program path (setq plz-curl-program "/usr/local/bin/curl") ;; Configure default curl arguments (setq plz-curl-default-args '("--silent" "--compressed" "--location")) ; Follow redirects ;; Set default connection timeout (seconds) (setq plz-connect-timeout 10) ;; Per-request timeout configuration (plz 'get "https://httpbin.org/delay/5" :connect-timeout 3 ; Max time to establish connection :timeout 10) ; Max total request time ;; Disable query on process kill (plz 'get "https://httpbin.org/get" :noquery t ; Don't ask to kill process on Emacs exit :then (lambda (body) (message "Done"))) ;; Send binary body (plz 'post "https://httpbin.org/post" :body (with-temp-buffer (insert-file-contents-literally "/path/to/binary-file") (buffer-string)) :body-type 'binary :as 'response) ;; Disable automatic response decoding (plz 'get "https://httpbin.org/encoding/utf8" :decode nil ; Return raw bytes :as 'binary) ``` -------------------------------- ### Synchronous Binary Download and Image Creation (Emacs Lisp) Source: https://github.com/alphapapa/plz.el/blob/master/README.org Downloads binary data (e.g., an image) synchronously from a URL and creates an Emacs image object from the downloaded data. The ':as 'binary' option retrieves raw data. ```elisp (let ((jpeg-data (plz 'get "https://httpbin.org/image/jpeg" :as 'binary))) (create-image jpeg-data nil 'data)) ``` -------------------------------- ### Queue Multiple Requests with Callback Source: https://context7.com/alphapapa/plz.el/llms.txt Manages a list of URLs, queues them for asynchronous processing with a concurrency limit, and executes a callback upon completion of all requests. Includes JSON parsing for responses. ```elisp ;; Queue multiple requests with finally callback (let ((queue (make-plz-queue :limit 2 :finally (lambda () (message "All requests complete!")))) (urls '("https://httpbin.org/get?n=1" "https://httpbin.org/get?n=2" "https://httpbin.org/get?n=3" "https://httpbin.org/get?n=4"))) (plz-run (dolist (url urls queue) (plz-queue queue 'get url :as #'json-read :then (lambda (data) (message "Received: %s" (alist-get 'url data))))))) ``` -------------------------------- ### Handle Streaming Responses with Custom Filters in Elisp Source: https://context7.com/alphapapa/plz.el/llms.txt Demonstrates how to use custom filters with the plz library to process streaming HTTP responses in real-time. This is useful for large downloads or server-sent events, allowing for chunk-by-chunk processing and accumulation of data. ```elisp ;; Custom filter for streaming response (let ((accumulated "")) (plz 'get "https://httpbin.org/stream/5" :filter (lambda (proc string) ;; Process each chunk as it arrives (setq accumulated (concat accumulated string)) (message "Received chunk: %d bytes" (length string)) ;; Must insert into process buffer for plz to work correctly (with-current-buffer (process-buffer proc) (goto-char (point-max)) (insert string))) :then (lambda (body) (message "Total received: %d bytes" (length accumulated))))) ;; Stream to buffer for live updates (let ((output-buffer (get-buffer-create "*Stream Output*"))) (plz 'get "https://httpbin.org/stream/10" :filter (lambda (proc string) (with-current-buffer (process-buffer proc) (goto-char (point-max)) (insert string)) ;; Also append to our output buffer (with-current-buffer output-buffer (goto-char (point-max)) (insert string))) :then (lambda (_) (message "Streaming complete")))) ``` -------------------------------- ### Synchronous HTTP Requests with plz Source: https://context7.com/alphapapa/plz.el/llms.txt Demonstrates making blocking HTTP requests using 'plz' where the response is returned directly. This includes setting timeouts for both connection and overall request duration, parsing JSON synchronously, and performing PUT, HEAD, and PATCH requests with specified bodies and headers. ```elisp ;; Simple synchronous GET (let ((response (plz 'get "https://httpbin.org/get"))) (message "Got %d bytes" (length response))) ;; Synchronous with timeout (seconds) (condition-case err (plz 'get "https://httpbin.org/delay/10" :timeout 5 :connect-timeout 3) (plz-error (message "Request failed: %s" (plz-error-message (cdr err))))) ;; Parse JSON response synchronously (let* ((data (plz 'get "https://httpbin.org/json" :as #'json-read)) (title (alist-get 'title (alist-get 'slideshow data)))) (message "Title: %s" title)) ;; => "Sample Slide Show" ;; PUT request with body (plz 'put "https://httpbin.org/put" :headers '(("Content-Type" . "application/json")) :body (json-encode '(("name" . "test") ("value" . 42))) :as #'json-read) ;; HEAD request (returns headers only) (plz 'head "https://httpbin.org/get" :as 'response) ;; => #s(plz-response 1.1 200 ((content-type . "application/json") ...) "") ;; PATCH request (plz 'patch "https://httpbin.org/patch" :headers '(("Content-Type" . "application/json")) :body (json-encode '(("field" . "updated"))) :as #'json-read) ``` -------------------------------- ### Asynchronous POST Request with JSON Handling (Emacs Lisp) Source: https://github.com/alphapapa/plz.el/blob/master/README.org Initiates an asynchronous HTTP POST request with a JSON body and custom headers. It parses the JSON response and calls a callback function with the result. Requires 'json-encode' for body serialization. ```elisp (plz 'post "https://httpbin.org/post" :headers '(("Content-Type" . "application/json")) :body (json-encode '(("key" . "value"))) :as #'json-read :then (lambda (alist) (message "Result: %s" (alist-get 'data alist)))) ``` -------------------------------- ### Access Detailed HTTP Response Structures in Elisp Source: https://context7.com/alphapapa/plz.el/llms.txt Shows how to retrieve and access the full HTTP response structure using plz, including version, status code, headers, and body. This allows for detailed inspection and parsing of server responses. ```elisp ;; Get full response structure (let ((response (plz 'get "https://httpbin.org/get" :as 'response))) (message "HTTP/%s %d" (plz-response-version response) (plz-response-status response)) (message "Content-Type: %s" (alist-get 'content-type (plz-response-headers response))) (message "Body length: %d" (length (plz-response-body response)))) ;; Access response structure slots (let ((resp (plz 'get "https://httpbin.org/response-headers?X-Custom=test" :as 'response))) (list :version (plz-response-version resp) ; => 1.1 or 2 :status (plz-response-status resp) ; => 200 :headers (plz-response-headers resp) ; => alist of headers :body (plz-response-body resp))) ;; Parse body from response structure (let* ((response (plz 'get "https://httpbin.org/json" :as 'response)) (json-data (with-temp-buffer (insert (plz-response-body response)) (goto-char (point-min)) (json-read)))) (alist-get 'slideshow json-data)) ``` -------------------------------- ### Async Error Handling with Response Status Source: https://context7.com/alphapapa/plz.el/llms.txt Implements asynchronous error handling where the `:else` callback inspects the HTTP status code of the response if it's an HTTP error. It provides distinct messages for 404, 500, and other HTTP errors, falling back to curl errors. ```elisp ;; Async error handling pattern (plz 'get "https://httpbin.org/status/404" :then (lambda (body) (message "Success: %s" body)) :else (lambda (err) (if-let ((response (plz-error-response err))) (pcase (plz-response-status response) (404 (message "Resource not found")) (500 (message "Server error")) (status (message "HTTP error: %d" status))) (message "Curl error: %s" (plz-error-message err))))) ``` -------------------------------- ### Request Queue: plz-queue Source: https://context7.com/alphapapa/plz.el/llms.txt Manage multiple HTTP requests with concurrency limits using `plz-queue`. Prevents overwhelming servers and controls request ordering. ```APIDOC ## Request Queue: plz-queue A queue system for managing multiple HTTP requests with concurrency limits. Prevents overwhelming servers and manages request ordering. ### Create a Request Queue Initializes a new request queue with a specified concurrency limit. ### Function `make-plz-queue` ### Parameters #### Keyword Arguments - **`:limit`** (integer) - Required - The maximum number of concurrent requests allowed in the queue. - **`:finally`** (function) - Optional - A callback function executed after all requests in the queue have completed. ### Request Example ```elisp ;; Create a queue with concurrency limit of 2 (defvar my-queue (make-plz-queue :limit 2)) ``` --- ### Queue and Run a Single Request Adds a request to the queue and starts processing it when a slot is available. ### Function `plz-run` with `plz-queue` ### Parameters #### Arguments for `plz-queue` - **`queue`** (plz-queue object) - The queue to add the request to. - **`method`** (symbol) - The HTTP method (e.g., `'get`). - **`url`** (string) - The URL for the request. - **`:then`** (function) - Optional - Callback for success. ### Request Example ```elisp ;; Queue and run a single request (plz-run (plz-queue my-queue 'get "https://httpbin.org/get?foo=0" :then (lambda (body) (message "Got: %s" (substring body 0 30))))) ``` --- ### Queue Multiple Requests Adds multiple requests to a queue, optionally with a global `:finally` callback. ### Function `plz-run` with `dolist` and `plz-queue` ### Parameters #### Arguments for `plz-queue` (within `dolist`) - **`queue`** (plz-queue object) - The queue to add requests to. - **`method`** (symbol) - The HTTP method. - **`url`** (string) - The URL for the request. - **`:as`** (symbol or list) - Optional - Response processing directive. - **`:then`** (function) - Optional - Callback for each request's success. ### Request Example ```elisp ;; Queue multiple requests with finally callback (let ((queue (make-plz-queue :limit 2 :finally (lambda () (message "All requests complete!")))) (urls '("https://httpbin.org/get?n=1" "https://httpbin.org/get?n=2" "https://httpbin.org/get?n=3" "https://httpbin.org/get?n=4"))) (plz-run (dolist (url urls queue) (plz-queue queue 'get url :as #'json-read :then (lambda (data) (message "Received: %s" (alist-get 'url data))))))) ``` ### Response #### Success Response (200) - **data** (any) - The processed response data for each request. #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Received: https://httpbin.org/get?n=1 ;; Received: https://httpbin.org/get?n=2 ;; Received: https://httpbin.org/get?n=3 ;; Received: https://httpbin.org/get?n=4 ;; All requests complete! ``` --- ### Check Queue Length Returns the number of pending requests in the queue. ### Function `plz-length` ### Parameters #### Arguments - **`queue`** (plz-queue object) - The queue to check. ### Request Example ```elisp ;; Check queue length (plz-length my-queue) ;; => 0 (when empty) ``` --- ### Clear Queue Removes all pending requests from the queue and cancels them. ### Function `plz-clear` ### Parameters #### Arguments - **`queue`** (plz-queue object) - The queue to clear. ### Request Example ```elisp ;; Clear queue and cancel pending requests (plz-clear my-queue) ``` --- ### Prepend High-Priority Request Adds a request to the very front of the queue, ensuring it's processed next. ### Function `plz-queue` with `'(prepend queue)` ### Parameters #### Arguments for `plz-queue` - **`'(prepend queue)`** - Special form to indicate prepending to the queue. - **`method`** (symbol) - The HTTP method. - **`url`** (string) - The URL for the request. - **`:then`** (function) - Optional - Callback for success. ### Request Example ```elisp ;; Prepend high-priority request to front of queue (plz-queue '(prepend my-queue) 'get "https://httpbin.org/get?priority=high" :then (lambda (body) (message "Priority request done"))) ``` ``` -------------------------------- ### plz Function API Source: https://github.com/alphapapa/plz.el/blob/master/README.org The main function `plz` is used to send HTTP requests. It supports both synchronous and asynchronous operations, with various options for customizing requests and handling responses. ```APIDOC ## plz Function ### Description Sends an HTTP request using curl. It can perform synchronous or asynchronous requests and returns the result based on the specified type. ### Method POST, GET, PUT, DELETE, etc. (determined by the `method` argument) ### Endpoint N/A (This is a function call, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (symbol or string) - The HTTP method (e.g., 'get, 'post). - **url** (string) - The URL to request. - **:key headers** (alist) - Optional. An alist of extra headers to send with the request. - **:key body** (string, buffer, or list) - Optional. The request body. Can be a string, buffer, or a list like `(file FILENAME)` to upload a file. - **:key else** (function) - Optional. Callback function for error handling. - **:key finally** (function) - Optional. Callback function to be executed in any case. - **:key noquery** (boolean) - Optional. If true, query parameters are not automatically appended. - **:key (as 'string)** (symbol) - Optional. Specifies the type of result to return or pass to the callback. Possible values include `buffer`, `binary`, `string`, `response`, `file`. - **:key (then 'sync)** (symbol or function) - Optional. For asynchronous requests, this can be a callback function. For synchronous requests, it's handled internally. - **:key (body-type 'text)** (symbol) - Optional. Specifies the type of the request body. Can be `text` or `binary`. - **:key (decode t)** (boolean) - Optional. Controls decoding of the response body. - **:key (decode-s)** (boolean) - Optional. Controls decoding of the response body for string output. - **:key (connect-timeout plz-connect-timeout)** (number) - Optional. Connection timeout in seconds. - **:key (timeout plz-timeout)** (number) - Optional. Total request timeout in seconds. ### Request Example ```elisp ;; Synchronous GET request, returning response body as string (plz 'get "https://httpbin.org/user-agent") ;; Synchronous GET request, parsing JSON response as alist (plz 'get "https://httpbin.org/get" :as #'json-read) ;; Asynchronous POST request with JSON body and callback (plz 'post "https://httpbin.org/post" :headers '(("Content-Type" . "application/json")) :body (json-encode '(("key" . "value"))) :as #'json-read :then (lambda (alist) (message "Result: %s" (alist-get 'data alist)))) ;; Synchronous download of a JPEG file (let ((jpeg-data (plz 'get "https://httpbin.org/image/jpeg" :as 'binary))) (create-image jpeg-data nil 'data)) ``` ### Response #### Success Response (200) - **result** (varies) - The type of the result depends on the `:as` parameter. It can be a string, binary data, an alist, a buffer, a `plz-response` structure, or a temporary filename. #### Response Example ```json { "user-agent": "curl/7.35.0" } ``` ``` -------------------------------- ### Prepend High-Priority Request Source: https://context7.com/alphapapa/plz.el/llms.txt Adds a high-priority request to the front of the queue, ensuring it is processed before other queued items. This is managed using a special `prepend` directive within `plz-queue`. ```elisp ;; Prepend high-priority request to front of queue (plz-queue '(prepend my-queue) 'get "https://httpbin.org/get?priority=high" :then (lambda (body) (message "Priority request done"))) ``` -------------------------------- ### Error Handling Source: https://context7.com/alphapapa/plz.el/llms.txt Provides mechanisms for handling various errors, including curl failures and HTTP status codes, with structured error types. ```APIDOC ## Error Handling Comprehensive error handling with structured error types for curl failures and HTTP errors. All errors inherit from `plz-error` for unified handling. ### Handle All `plz` Errors Uniformly Uses `condition-case` to catch any `plz-error` and extract general error information. ### Conditions - **`plz-error`** - Base condition for all PLZ errors. ### Parameters #### Error Object (`err`) - **`plz-error-message`** (function) - Returns the main error message. - **`plz-error-curl-error`** (function) - Returns a list `(code message)` for curl-specific errors. ### Request Example ```elisp ;; Handle all plz errors uniformly (condition-case err (plz 'get "https://invalid-domain.example/") (plz-error (let ((error-data (cdr err))) (message "Error: %s" (plz-error-message error-data)) (when-let ((curl-err (plz-error-curl-error error-data))) (message "Curl code %d: %s" (car curl-err) (cdr curl-err)))))) ``` ### Response #### Error Response - **`err`** (error object) - Contains details about the `plz-error`. #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Error: Could not resolve host: invalid-domain.example ;; Curl code 6: Couldn't resolve host name ``` --- ### Handle HTTP Errors Specifically Catches `plz-http-error` to specifically handle errors returned by the HTTP server. ### Conditions - **`plz-http-error`** - Condition for HTTP status code errors (e.g., 4xx, 5xx). ### Parameters #### Error Object (`err`) - **`plz-error-response`** (function) - Returns the HTTP response object associated with the error. - **`plz-response-status`** (function) - Returns the HTTP status code from a response object. ### Request Example ```elisp ;; Handle HTTP errors specifically (condition-case err (plz 'get "https://httpbin.org/status/403") (plz-http-error (let* ((error-data (cdr err)) (response (plz-error-response error-data))) (message "HTTP %d: Access denied" (plz-response-status response))))) ``` ### Response #### Error Response - **`err`** (error object) - Contains details about the `plz-http-error`. #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; HTTP 403: Access denied ``` --- ### Async Error Handling Pattern Uses the `:else` callback in asynchronous requests to handle errors gracefully. ### Method GET ### Endpoint `https://httpbin.org/status/404` ### Parameters #### Query Parameters - **`then`** (function) - Callback for success. - **`else`** (function) - Callback for errors. Receives the error object. ### Request Example ```elisp ;; Async error handling pattern (plz 'get "https://httpbin.org/status/404" :then (lambda (body) (message "Success: %s" body)) :else (lambda (err) (if-let ((response (plz-error-response err))) (pcase (plz-response-status response) (404 (message "Resource not found")) (500 (message "Server error")) (status (message "HTTP error: %d" status))) (message "Curl error: %s" (plz-error-message err))))) ``` ### Response #### Success Response (200) - **body** (string) - The response body. #### Error Response - **`err`** (error object) - Contains details about the error (HTTP or curl). #### Response Example ```elisp ;; Example output for a 404 error: ;; Resource not found ``` --- ### Timeout Handling Catches `plz-curl-error` specifically for timeouts using a `:timeout` parameter. ### Conditions - **`plz-curl-error`** - Condition for curl-specific errors. ### Parameters #### Request Parameters - **`:timeout`** (number) - The timeout in seconds for the request. #### Error Object (`err`) - **`plz-error-curl-error`** (function) - Returns a list `(code message)` for curl-specific errors. Code `28` indicates a timeout. ### Request Example ```elisp ;; Timeout handling (condition-case err (plz 'get "https://httpbin.org/delay/10" :timeout 2) (plz-curl-error (let ((curl-err (plz-error-curl-error (cdr err)))) (when (= 28 (car curl-err)) ; Curl timeout error code (message "Request timed out"))))) ``` ### Response #### Error Response - **`err`** (error object) - Contains details about the `plz-curl-error`. #### Response Example ```elisp ;; Example output in the *Messages* buffer: ;; Request timed out ``` ``` -------------------------------- ### Check Queue Length Source: https://context7.com/alphapapa/plz.el/llms.txt Retrieves the current number of pending requests in a queue. Returns 0 if the queue is empty and has no active requests. ```elisp ;; Check queue length (plz-length my-queue) ;; => 0 (when empty) ``` -------------------------------- ### Timeout Error Handling Source: https://context7.com/alphapapa/plz.el/llms.txt Demonstrates how to catch `plz-curl-error` specifically for timeouts. It checks for the curl error code 28, which indicates a timeout, and provides a user-friendly message. ```elisp ;; Timeout handling (condition-case err (plz 'get "https://httpbin.org/delay/10" :timeout 2) (plz-curl-error (let ((curl-err (plz-error-curl-error (cdr err)))) (when (= 28 (car curl-err)) ; Curl timeout error code (message "Request timed out"))))) ``` -------------------------------- ### Handle Specific HTTP Errors Source: https://context7.com/alphapapa/plz.el/llms.txt Catches and specifically handles `plz-http-error` exceptions, such as 403 Forbidden responses. It extracts the HTTP status code from the error response for targeted handling. ```elisp ;; Handle HTTP errors specifically (condition-case err (plz 'get "https://httpbin.org/status/403") (plz-http-error (let* ((error-data (cdr err)) (response (plz-error-response error-data))) (message "HTTP %d: Access denied" (plz-response-status response))))) ``` -------------------------------- ### Clear Request Queue Source: https://context7.com/alphapapa/plz.el/llms.txt Empties the request queue and cancels any requests that are currently in progress. This is useful for aborting pending operations. ```elisp ;; Clear queue and cancel pending requests (plz-clear my-queue) ``` -------------------------------- ### Handle General plz Errors Source: https://context7.com/alphapapa/plz.el/llms.txt Catches and processes errors that inherit from `plz-error`, including network issues like invalid domains. It extracts and displays a user-friendly error message and specific curl error details. ```elisp ;; Handle all plz errors uniformly (condition-case err (plz 'get "https://invalid-domain.example/") (plz-error (let ((error-data (cdr err))) (message "Error: %s" (plz-error-message error-data)) (when-let ((curl-err (plz-error-curl-error error-data))) (message "Curl code %d: %s" (car curl-err) (cdr curl-err)))))) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.