### Certificates usage example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Example of retrieving the first certificate. ```ruby cert = connection.certificates.first puts cert.certificate ``` -------------------------------- ### Install with gem install Source: https://github.com/socketry/cloudflare/blob/main/readme.md Install the gem directly from the command line. ```shell $ gem install cloudflare ``` -------------------------------- ### Accounts usage example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Example of accessing account KV namespaces. ```ruby account = connection.accounts.first namespace = account.kv_namespaces ``` -------------------------------- ### Zones usage example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Example of retrieving a zone by name. ```ruby zones = connection.zones zone = zones.find_by_name("example.com") ``` -------------------------------- ### User usage example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Example of retrieving the authenticated user's email. ```ruby user = connection.user puts user.email ``` -------------------------------- ### Basic iteration and find_by_id examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/paginate.md Shows basic iteration over zones, explicit pagination parameters, and lazy access to a resource by id. The lazy access triggers the GET only when an attribute is accessed. ```ruby # List all zones: connection.zones.each do |zone| puts zone.name end # Explicit pagination parameters: connection.zones.each(page: 2, per_page: 100) {|zone| puts zone.id} # Lazy access to a resource by id: zone = connection.zones.find_by_id("abc123") puts zone.name # triggers the GET ``` -------------------------------- ### CIDR query examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Examples of querying IP ranges with and without ipv filter. ```ruby connection.cidrs # => ["173.245.48.0/20", ..., "2400:cb00::/32", ...] ``` ```ruby connection.cidrs(ipv: 6) # => ["2400:cb00::/32", ...] ``` -------------------------------- ### Install with Bundler Source: https://github.com/socketry/cloudflare/blob/main/readme.md Add the gem to your application's Gemfile and run bundle to install. ```ruby gem "cloudflare" ``` -------------------------------- ### Create DNS record example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/dns.md Example call to create an A record with proxied option disabled. ```ruby record = zone.dns_records.create("A", "batman", "1.2.3.4", proxied: false) ``` -------------------------------- ### Rename namespace example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Renames a namespace and prints the updated title. ```ruby namespace.rename("New Title") puts namespace.title # "New Title" ``` -------------------------------- ### Create KV namespace and write value Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/accounts.md Example of creating a KV namespace and writing a value. ```ruby account = connection.accounts.first namespace = account.kv_namespaces.create("My Worker Store") namespace.write_value("key", "value") ``` -------------------------------- ### Create namespace example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Creates a KV namespace with the title "My Worker Store". ```ruby namespace = account.kv_namespaces.create("My Worker Store") ``` -------------------------------- ### initialize message examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/request-error.md Examples from the test suite showing the message format for RequestError.new with different payloads. ```ruby RequestError.new("GET /api/v1/test", {error: "Authentication failed"}).message # => "GET /api/v1/test: Authentication failed" ``` ```ruby RequestError.new("DELETE /api/v1/test", "Resource not found").message # => "DELETE /api/v1/test: \"Resource not found\"" ``` -------------------------------- ### Key + email authentication example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Authentication using API key and email, producing x-auth-key and x-auth-email headers. ```ruby connection = Cloudflare.connect(key: ENV["CLOUDFLARE_KEY"], email: ENV["CLOUDFLARE_EMAIL"]) ``` -------------------------------- ### Bearer token authentication example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Recommended authentication method using a Cloudflare API token. ```ruby connection = Cloudflare.connect(token: "a_generated_api_token") ``` -------------------------------- ### update_settings usage examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostnames.md Shows updating SSL settings and updating metadata and origin together. ```ruby hostname.update_settings(ssl: {method: "cname", type: "dv"}) hostname.update_settings(metadata: {color: "red"}, origin: "origin.example.com") ``` -------------------------------- ### Find namespace by title example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Finds a namespace with the title "My Worker Store". ```ruby namespace = account.kv_namespaces.find_by_title("My Worker Store") ``` -------------------------------- ### Example usage of Cloudflare::Zones#create Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/zones.md Creates a zone for example.com using the first account from the connection. The comment shows the resulting POST request. ```ruby account = connection.accounts.first zone = connection.zones.create("example.com", account) # POST /zones {name: "example.com", account: {id: "..."}, jump_start: false} ``` -------------------------------- ### Iterate namespace keys and print names Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Example usage of #name: iterates over all keys in a namespace and prints each key name. ```ruby namespace.keys.each {|key| puts key.name} ``` -------------------------------- ### Create custom hostname examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostnames.md Shows two calls to #create: one with default ssl options and one with custom ssl and metadata. The first posts {hostname: "www.example.com", ssl: {method: "http", type: "dv"}}. ```ruby hostname = zone.custom_hostnames.create("www.example.com") # POST /zones/{id}/custom_hostnames {hostname: "www.example.com", ssl: {method: "http", type: "dv"}} hostname = zone.custom_hostnames.create("www.example.com", ssl: {method: "cname"}, metadata: {env: "prod"}) ``` -------------------------------- ### Find DNS record by name example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/dns.md Example call to find a record by its full name. ```ruby record = zone.dns_records.find_by_name("www.example.com") ``` -------------------------------- ### User-service key authentication example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Authentication using API key without email, producing x-auth-user-service-key header. ```ruby connection = Cloudflare::Connection.open.authenticated(key: ENV["SERVICE_KEY"]) ``` -------------------------------- ### Full lifecycle example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/firewall.md Clears existing rules, sets whitelist and block rules, verifies, then deletes the block rule. ```ruby rules = zone.firewall_rules # Clear existing rules, then set new ones: rules.each {|rule| rule.delete} whitelist_rule = rules.set("whitelist", "123.123.123.123") block_rule = rules.set("block", "123.123.123.124", notes: "gemtest") p whitelist_rule.configuration # {target: "ip", value: "123.123.123.123"} p rules.each_by_value("123.123.123.124").to_a.size # 1 block_rule.delete ``` -------------------------------- ### Set rule example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/firewall.md Creates a block rule for IP 1.2.3.4 with notes, then prints the mode. ```ruby rule = zone.firewall_rules.set("block", "1.2.3.4", notes: "ssh dictionary attack") p rule.mode # "block" ``` -------------------------------- ### GET /accounts/{id}/storage/kv/namespaces/{nid}/keys Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists all keys in a KV namespace. Supports pagination. ```APIDOC ## GET /accounts/{id}/storage/kv/namespaces/{nid}/keys ### Description Lists all keys in a KV namespace. Supports pagination. ### Method GET ### Endpoint /accounts/{id}/storage/kv/namespaces/{nid}/keys ### Parameters #### Path Parameters - **id** (string) - Required - The account ID. - **nid** (string) - Required - The namespace ID. #### Query Parameters - **page** (integer) - Optional - Page number for pagination. - **per_page** (integer) - Optional - Number of items per page. ### Response #### Success Response (200) - **result** (array) - List of KV::Key objects. - **result_info** (object) - Pagination metadata. #### Response Example { "result": [ { "name": "key_name", "expiration": "optional_expiration" } ], "result_info": { "page": 1, "per_page": 20, "total_pages": 1, "count": 1, "total_count": 1 } } ``` -------------------------------- ### purge_cache method and usage examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/zones.md Posts to /zones/{id}/purge_cache. With no arguments it purges everything ({purge_everything: true}); with arguments, options are sent as-is (e.g., purge by files or tags). The return value is the response of self.class.post. ```ruby DEFAULT_PURGE_CACHE_PARAMETERS = { purge_everything: true }.freeze def purge_cache(**options) if options.empty? options = DEFAULT_PURGE_CACHE_PARAMETERS end self.class.post(@resource.with(path: "purge_cache"), options) end ``` ```ruby zone.purge_cache # POST /zones/{id}/purge_cache {purge_everything: true} zone.purge_cache(files: ["http://example.com/css/styles.css"]) # POST /zones/{id}/purge_cache {files: [...]} ``` -------------------------------- ### Using Entry#to_s and result Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/logs.md Example usage of the Entry to_s method and accessing the full log line hash. ```ruby log = zone.logs.first puts log.to_s # e.g. "53d0ce5e2ad6e4e3-/robots.txt" p log.result # full log line hash (any Cloudflare log field) ``` -------------------------------- ### Fetch current user example Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/user.md Retrieves the current user via connection.user and prints id and email. The representation is lazy; the HTTP request occurs when an attribute is read. ```ruby user = connection.user puts user.id # 32-char hex string puts user.email # e.g. "admin@example.com" ``` -------------------------------- ### Example usage of Cloudflare::Zones#find_by_name Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/zones.md Finds a zone by name. The comment shows the resulting GET request with pagination parameters. ```ruby zone = connection.zones.find_by_name("example.com") # GET /zones?page=1&per_page=50&name=example.com ... ``` -------------------------------- ### KV Namespace Lifecycle Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Demonstrates the complete lifecycle of a KV namespace: create, write, read, list, delete, rename, and delete namespace. ```APIDOC ## KV Namespace Lifecycle ### Description Demonstrates the complete lifecycle of a KV namespace: create, write, read, list, delete, rename, and delete namespace. ### Methods - `account.kv_namespaces.create(title)` - Creates a new KV namespace. - `namespace.write_value(key, value)` - Writes a value to a key. - `namespace.read_value(key)` - Reads the value for a key. - `namespace.keys` - Lists all keys in the namespace. - `namespace.delete_value(key)` - Deletes a key-value pair. - `namespace.rename(new_title)` - Renames the namespace. - `namespace.delete` - Deletes the namespace. ### Parameters #### create - `title` (String) - Required - The title of the namespace. #### write_value - `key` (String) - Required - The key to write. - `value` (String/Number) - Required - The value to store. #### read_value - `key` (String) - Required - The key to read. #### delete_value - `key` (String) - Required - The key to delete. #### rename - `new_title` (String) - Required - The new title for the namespace. ### Request Example ```ruby account = connection.accounts.first namespace = account.kv_namespaces.create("Test Worker #{SecureRandom.hex(4)}") namespace.write_value("key-1", 123) puts namespace.read_value("key-1") puts namespace.keys.map(&:name).sort namespace.delete_value("key-2") namespace.rename(namespace.title + " Renamed") namespace.delete ``` ### Response #### Success Response - `namespace.id` (String) - 32-char hex identifier. - `namespace.title` (String) - The title of the namespace. - `write_value` returns `true` on success. - `read_value` returns the stored value as a binary string. - `keys` returns a collection of key objects with `name` attribute. - `delete_value` returns `true` on success. - `rename` returns `true` on success. - `delete` returns `true` on success. #### Response Example ```ruby puts namespace.id # 32-char hex puts namespace.title namespace.write_value("key-1", 123) # => true puts namespace.read_value("key-1") # => "123" (binary string) puts namespace.keys.map(&:name).sort # ["key-1", "key-2"] puts namespace.delete_value("key-2") # => true namespace.rename(namespace.title + " Renamed") puts namespace.title ``` ``` -------------------------------- ### Error Handling Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Shows how to handle errors when reading a missing key or renaming with an empty title. ```APIDOC ## Error Handling ### Description Shows how to handle errors when reading a missing key or renaming with an empty title. ### Methods - `namespace.read_value(key)` - Reads a value; raises `Cloudflare::RequestError` if key is missing. - `namespace.rename(new_title)` - Renames the namespace; raises `Cloudflare::RequestError` if title is empty. ### Parameters #### read_value - `key` (String) - Required - The key to read. #### rename - `new_title` (String) - Required - The new title for the namespace. ### Request Example ```ruby begin namespace.read_value("missing-key") rescue Cloudflare::RequestError => e warn "KV read failed: #{e.message}" end begin namespace.rename("") # empty title rejected by API rescue Cloudflare::RequestError => e warn "Rename failed: #{e.message}" end ``` ### Response #### Error Response - `Cloudflare::RequestError` - Raised when the API returns an error (e.g., missing key or invalid title). ``` -------------------------------- ### error_string_for examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/request-error.md Examples from the test suite showing how error_string_for renders different payloads: Hash with :error, Hash with :errors array, plain string, and nil. ```ruby RequestError.error_string_for({error: "Something went wrong"}) # => "Something went wrong" ``` ```ruby RequestError.error_string_for({errors: [{message: "First error"}, {message: "Second error"}]}) # => "First error, Second error" ``` ```ruby RequestError.error_string_for("Plain error message") # => "\"Plain error message\"" ``` ```ruby RequestError.error_string_for(nil) # => "nil" ``` -------------------------------- ### GET /certificates/{id} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Fetches a specific certificate by its ID. Returns a Certificate object. ```APIDOC ## GET /certificates/{id} ### Description Fetches a specific certificate by its ID. Returns a Certificate object. ### Method GET ### Endpoint /certificates/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Certificate ID ### Response #### Success Response (200) - **certificate** (object) - Certificate object #### Response Example { "certificate": {} } ``` -------------------------------- ### Cloudflare::KV::Namespace#keys Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Returns a paginated collection of keys for the namespace. ```APIDOC ## `#keys` ### Description Returns a `Cloudflare::KV::Keys` collection bound to the namespace's keys endpoint. ### Method GET ### Endpoint `/accounts/{account_id}/storage/kv/namespaces/{namespace_id}/keys` ### Response #### Success Response (200) - **keys** (Array) - List of key names. #### Response Example ```json { "keys": ["key1", "key2"] } ``` ``` -------------------------------- ### Catching RequestError Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/request-error.md Example showing how to rescue Cloudflare::RequestError and access the message and raw payload. ```ruby require "cloudflare" zone = Cloudflare.connect(token: ENV["CLOUDFLARE_TOKEN"]).zones.find_by_id("missing-zone") begin puts zone.name rescue Cloudflare::RequestError => e puts "Request failed: #{e.message}" # includes request + API error string puts "Raw payload: #{e.value.inspect}" # full failure hash from Cloudflare end ``` -------------------------------- ### Map keys to names Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Maps each key in the namespace to its name using the Keys collection. ```ruby names = namespace.keys.map(&:name) ``` -------------------------------- ### GET /certificates Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists certificates with pagination support. Returns a paginated list of Certificate objects. ```APIDOC ## GET /certificates ### Description Lists certificates with pagination support. Returns a paginated list of Certificate objects. ### Method GET ### Endpoint /certificates ### Parameters #### Query Parameters - **page** (integer) - Optional - Page number for pagination - **per_page** (integer) - Optional - Number of items per page ### Response #### Success Response (200) - **certificates** (array) - List of Certificate objects #### Response Example { "certificates": [] } ``` -------------------------------- ### GET /accounts Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists all accounts with pagination support. Returns a paginated list of Account objects. ```APIDOC ## GET /accounts ### Description Lists all accounts with pagination support. Returns a paginated list of Account objects. ### Method GET ### Endpoint /accounts ### Parameters #### Query Parameters - **page** (integer) - Optional - Page number for pagination. - **per_page** (integer) - Optional - Number of items per page. ### Response #### Success Response (200) - **result** (array) - List of Account objects. - **result_info** (object) - Pagination metadata (page, per_page, total_pages, etc.). #### Response Example { "result": [ { "id": "account_id", "name": "account_name" } ], "result_info": { "page": 1, "per_page": 20, "total_pages": 1, "count": 1, "total_count": 1 } } ``` -------------------------------- ### Cloudflare::KV::Namespaces#create Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Creates a new KV namespace by POSTing to /accounts/{account_id}/storage/kv/namespaces. Returns a new Cloudflare::KV::Namespace bound to the created namespace. ```APIDOC ## [POST] /accounts/{account_id}/storage/kv/namespaces ### Description Creates a new KV namespace. ### Method POST ### Endpoint /accounts/{account_id}/storage/kv/namespaces ### Parameters #### Path Parameters - **account_id** (string) - Required - The account identifier. #### Request Body - **title** (string) - Required - Namespace title. - **options** (object) - Optional - Extra payload keys (Cloudflare accepts `title` only here in practice). ### Request Example { "title": "My Worker Store" } ### Response #### Success Response (200) - **result** (object) - Contains the created namespace details. - **result.id** (string) - The namespace ID. #### Response Example { "result": { "id": "namespace_id" } } ``` -------------------------------- ### Require paths for SSLAttribute and Settings Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostname-ssl-attribute.md Import the SSLAttribute and Settings classes from the cloudflare gem. ```ruby require "cloudflare/custom_hostname/ssl_attribute" require "cloudflare/custom_hostname/ssl_attribute/settings" ``` -------------------------------- ### GET /user Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Retrieves the current user information. Returns a User representation with id and email fields. ```APIDOC ## GET /user ### Description Retrieves the current user information. Returns a User representation with id and email fields. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **id** (string) - User ID - **email** (string) - User email #### Response Example { "id": "string", "email": "string" } ``` -------------------------------- ### Inspect resource path for kv_namespaces Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/accounts.md Shows how to inspect the resource path of the kv_namespaces collection. ```ruby namespace = account.kv_namespaces namespace.resource.reference.path.end_with?("/#{account.id}/storage/kv/namespaces") # true ``` -------------------------------- ### Cloudflare.connect implementation Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/cloudflare.md Defines the .connect class method. It opens a connection, optionally authenticates, and yields it in a Sync block if a block is given, ensuring the connection is closed. ```ruby module Cloudflare def self.connect(*arguments, **auth_info) connection = Connection.open(*arguments) if !auth_info.empty? connection = connection.authenticated(**auth_info) end return connection unless block_given? Sync do yield connection ensure connection.close end end end ``` -------------------------------- ### Settings#initialize Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostname-ssl-attribute.md Initializes a new Settings object wrapping the SSL settings hash. The hash is shared with the parent SSLAttribute, so writes propagate. ```APIDOC ## Settings#initialize ### Description Initializes a new Settings object wrapping the SSL settings hash. The hash is shared with the parent SSLAttribute, so writes propagate. ### Method initialize ### Parameters - `settings` (Hash) - Optional - Default: `{}` - The raw settings hash to wrap. ### Request Example ```ruby settings = Settings.new({ ciphers: ["ECDHE-RSA-AES128-GCM-SHA256"], http2: "on" }) ``` ``` -------------------------------- ### GET /accounts/{id}/storage/kv/namespaces Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists all KV namespaces for a given account. Supports pagination and can be filtered by title. ```APIDOC ## GET /accounts/{id}/storage/kv/namespaces ### Description Lists all KV namespaces for a given account. Supports pagination and can be filtered by title. ### Method GET ### Endpoint /accounts/{id}/storage/kv/namespaces ### Parameters #### Path Parameters - **id** (string) - Required - The account ID. #### Query Parameters - **page** (integer) - Optional - Page number for pagination. - **per_page** (integer) - Optional - Number of items per page. ### Response #### Success Response (200) - **result** (array) - List of KV::Namespace objects. - **result_info** (object) - Pagination metadata. #### Response Example { "result": [ { "id": "namespace_id", "title": "namespace_title" } ], "result_info": { "page": 1, "per_page": 20, "total_pages": 1, "count": 1, "total_count": 1 } } ``` -------------------------------- ### ssl_active? usage examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostnames.md Shows passive check without request and forced check that may trigger a validation request. ```ruby hostname.ssl_active? # passive check, no request hostname.ssl_active?(true) # may trigger a validation request ``` -------------------------------- ### Cloudflare::KV::Namespaces#create Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md POSTs a new namespace to /accounts/{account_id}/storage/kv/namespaces. Returns a new Cloudflare::KV::Namespace bound to .../namespaces/{namespace_id}. ```ruby def create(title, **options) payload = {title: title, **options} Namespace.post(@resource, payload) do |resource, response| value = response.read result = value[:result] metadata = response.headers if id = result[:id] resource = resource.with(path: id) end Namespace.new(resource, value: value, metadata: metadata) end end ``` -------------------------------- ### GET /accounts/{id} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Fetches a single account by its ID. This is a lazy fetch, meaning the account data is retrieved on demand. ```APIDOC ## GET /accounts/{id} ### Description Fetches a single account by its ID. This is a lazy fetch, meaning the account data is retrieved on demand. ### Method GET ### Endpoint /accounts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The account ID. ### Response #### Success Response (200) - **result** (object) - The Account object. #### Response Example { "result": { "id": "account_id", "name": "account_name" } } ``` -------------------------------- ### GET /ips Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Retrieves Cloudflare IP address ranges (CIDRs). Optionally filter by IP version (IPv4 or IPv6). ```APIDOC ## [GET] /ips ### Description Retrieves Cloudflare IP address ranges (CIDRs). Optionally filter by IP version (IPv4 or IPv6). ### Method GET ### Endpoint /ips ### Parameters #### Query Parameters - **ipv** (string) - Optional - IP version to filter: 'ipv4' or 'ipv6'. If omitted, both families are returned. ### Response #### Success Response (200) - **result.ipv4_cidrs** (array of strings) - IPv4 CIDR blocks. - **result.ipv6_cidrs** (array of strings) - IPv6 CIDR blocks. #### Response Example { "result": { "ipv4_cidrs": ["192.0.2.0/24"], "ipv6_cidrs": ["2001:db8::/32"] } } ``` -------------------------------- ### Distinguishing failure classes via payload Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/request-error.md Example showing how to inspect e.value to distinguish API error envelopes from other failure types. ```ruby begin connection.zones.create("example.com", account) rescue Cloudflare::RequestError => e case e.value when Hash # API error envelope: p e.value[:errors] # [{code: 81057, message: "..."}] per Cloudflare docs end end ``` -------------------------------- ### Iteration with to_s Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/firewall.md Prints each rule's string form. ```ruby zone.firewall_rules.each do |rule| puts rule.to_s # "1.2.3.4 - block - gemtest" end ``` -------------------------------- ### Require cloudflare Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/cloudflare.md Loads the gem's entry point, which loads Async and the Cloudflare::Connection class. ```ruby require "cloudflare" ``` -------------------------------- ### Require cloudflare/kv/namespaces and cloudflare/kv/wrapper Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Import path for the KV module. Requires both the namespaces and the transport wrapper files. ```ruby require "cloudflare/kv/namespaces" require "cloudflare/kv/wrapper" # transport wrapper ``` -------------------------------- ### Shared hash example with settings Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostname-ssl-attribute.md Shows that mutating the Settings object updates the underlying params hash, as seen in to_h. ```ruby attr = hostname.ssl attr.settings.min_tls_version = "1.2" attr.to_h[:settings][:min_tls_version] # "1.2" — shared hash ``` -------------------------------- ### GET /zones/{id}/logs/received Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists received logs for a zone with pagination. Returns a paginated list of Logs::Entry objects. ```APIDOC ## [GET] /zones/{id}/logs/received ### Description Lists received logs for a zone with pagination. Returns a paginated list of Logs::Entry objects. ### Method GET ### Endpoint /zones/{id}/logs/received ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID #### Query Parameters - **page** (integer) - Required - Page number for pagination - **per_page** (integer) - Required - Number of items per page ### Response #### Success Response (200) - **result** (array) - Paginated list of Logs::Entry objects #### Response Example { "result": [ { "id": "log_id", "timestamp": "2023-01-01T00:00:00Z", "message": "Request received" } ] } ``` -------------------------------- ### Using any account-like representation with Zones#create Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/accounts.md Any representation responding to to_id can be passed as the account argument. ```ruby # Any of these work: account = connection.accounts.first account = connection.accounts.find_by_id(ACCOUNT_ID) account = connection.accounts.find_by_id("...") # lazy zone = connection.zones.create("example.com", account) # POST /zones {name: "example.com", account: {id: account.id}, jump_start: false} ``` -------------------------------- ### #name Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/dns.md Returns the record name, e.g. "www.example.com". ```APIDOC ## #name ### Description Returns the record name, e.g. `"www.example.com"`. ### Method GET ### Endpoint /zones/{id}/dns_records/{record_id} ### Response #### Success Response (200) - **name** (String) - Record name #### Response Example ```json { "name": "www.example.com" } ``` ``` -------------------------------- ### GET /zones/{id} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Retrieves a specific zone by ID. The response is lazy; the zone data is fetched on first attribute access. ```APIDOC ## [GET] /zones/{id} ### Description Retrieves a specific zone by ID. The response is lazy; the zone data is fetched on first attribute access. ### Method GET ### Endpoint /zones/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID ### Response #### Success Response (200) - **result** (object) - Zone object #### Response Example { "result": { "id": "zone_id", "name": "example.com" } } ``` -------------------------------- ### GET /zones Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists zones with pagination and optional name filtering. Returns a paginated result array, each item wrapped as a Zone. ```APIDOC ## [GET] /zones ### Description Lists zones with pagination and optional name filtering. Returns a paginated result array, each item wrapped as a Zone. ### Method GET ### Endpoint /zones ### Parameters #### Query Parameters - **page** (integer) - Required - Page number for pagination - **per_page** (integer) - Required - Number of items per page - **name** (string) - Optional - Filter zones by name ### Response #### Success Response (200) - **result** (array) - Paginated list of Zone objects #### Response Example { "result": [ { "id": "zone_id", "name": "example.com" } ] } ``` -------------------------------- ### User#email Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/user.md Returns the user's email address. This method triggers a GET /user request if the representation has not been loaded yet. ```APIDOC ## User#email ### Description Returns the user's email address. This method triggers a GET /user request if the representation has not been loaded yet. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **email** (string) - The user's email address. #### Response Example { "email": "admin@example.com" } ``` -------------------------------- ### Require cloudflare/connection Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/connection.md Import path for the Cloudflare::Connection class. ```ruby require "cloudflare/connection" ``` -------------------------------- ### Listing and fetching accounts Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/accounts.md Pattern from test/cloudflare/accounts.rb: force fetch first account, list all, fetch specific. ```ruby # Force a fetch of the first account: first_account = connection.accounts.first puts first_account.id # List all accounts: connection.accounts.each do |account| puts account.id end # Fetch a specific account: fetched = connection.accounts.find_by_id(first_account.id) puts fetched.id ``` -------------------------------- ### Complete KV lifecycle Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Mirrors test/cloudflare/kv/namespaces.rb. Creates a namespace, writes/reads values, lists keys, deletes a value, renames, and cleans up in an ensure block. read_value returns a binary string; write_value returns true. ```ruby account = connection.accounts.first namespace = account.kv_namespaces.create("Test Worker #{SecureRandom.hex(4)}") begin puts namespace.id # 32-char hex puts namespace.title namespace.write_value("key-1", 123) # => true puts namespace.read_value("key-1") # => "123" (binary string) namespace.write_value("key-2", "value-2") puts namespace.keys.map(&:name).sort # ["key-1", "key-2"] puts namespace.delete_value("key-2") # => true namespace.rename(namespace.title + " Renamed") puts namespace.title ensure namespace.delete end ``` -------------------------------- ### Listing and fetching existing certificates Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/certificates.md Iterates over certificates, prints id and PEM body, and fetches by id. ```ruby connection.certificates.each do |cert| puts cert.id puts cert.certificate # PEM body end fetched = connection.certificates.find_by_id(cert_id) puts fetched.certificate ``` -------------------------------- ### update_content usage examples Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/dns.md Shows updating a record's content, optionally with extra options like proxied: true. ```ruby record = zone.dns_records.find_by_name("www.example.com") record.update_content("4.3.2.1") # keeps type/name, new content record.update_content("4.3.2.1", proxied: true) # non-trivial option ``` -------------------------------- ### User#id Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/user.md Returns the user id as a 32-character hex string. This method triggers a GET /user request if the representation has not been loaded yet. ```APIDOC ## User#id ### Description Returns the user id as a 32-character hex string. This method triggers a GET /user request if the representation has not been loaded yet. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **id** (string) - The user id, a 32-character hex string. #### Response Example { "id": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" } ``` -------------------------------- ### Cloudflare::KV::Namespace#title Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Returns the namespace's display title. ```APIDOC ## `#title` ### Description Returns the namespace's display title. ### Method GET ### Endpoint `/accounts/{account_id}/storage/kv/namespaces/{namespace_id}` ### Response #### Success Response (200) - **title** (String) - The namespace's display title. #### Response Example ```json { "title": "My Namespace" } ``` ``` -------------------------------- ### Error handling with RequestError Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/paginate.md Shows how requests raised while iterating propagate as Cloudflare::RequestError, with an example rescue block that prints an error message to stderr. ```ruby begin connection.zones.each {|zone| puts zone.name} rescue Cloudflare::RequestError => e $stderr.puts "Failed to list zones: #{e.message}" end ``` -------------------------------- ### Settings class initialization Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostname-ssl-attribute.md Initializes the Settings wrapper around a raw settings hash. The hash is shared with the parent SSLAttribute via ||=, so writes propagate. ```ruby class Settings def initialize(settings = {}) @settings = settings end ``` -------------------------------- ### GET /accounts/{id}/storage/kv/namespaces/{nid} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Fetches a single KV namespace by its ID. This is a lazy fetch, meaning the namespace data is retrieved on demand. ```APIDOC ## GET /accounts/{id}/storage/kv/namespaces/{nid} ### Description Fetches a single KV namespace by its ID. This is a lazy fetch, meaning the namespace data is retrieved on demand. ### Method GET ### Endpoint /accounts/{id}/storage/kv/namespaces/{nid} ### Parameters #### Path Parameters - **id** (string) - Required - The account ID. - **nid** (string) - Required - The namespace ID. ### Response #### Success Response (200) - **result** (object) - The KV::Namespace object. #### Response Example { "result": { "id": "namespace_id", "title": "namespace_title" } } ``` -------------------------------- ### GET /zones/{id}/custom_hostnames Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists custom hostnames for a zone with pagination and optional filtering by hostname. Returns a paginated list of CustomHostname objects. ```APIDOC ## [GET] /zones/{id}/custom_hostnames ### Description Lists custom hostnames for a zone with pagination and optional filtering by hostname. Returns a paginated list of CustomHostname objects. ### Method GET ### Endpoint /zones/{id}/custom_hostnames ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID #### Query Parameters - **page** (integer) - Required - Page number for pagination - **per_page** (integer) - Required - Number of items per page - **hostname** (string) - Optional - Filter custom hostnames by hostname ### Response #### Success Response (200) - **result** (array) - Paginated list of CustomHostname objects #### Response Example { "result": [ { "id": "hostname_id", "hostname": "custom.example.com", "ssl": { "method": "http", "type": "dv" } } ] } ``` -------------------------------- ### Private value_representation method Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Builds a Value representation for a key name with the octet-stream wrapper. ```ruby private def value_representation(name) self.with(Value, path: "values/#{name}/") end ``` -------------------------------- ### Cloudflare::KV::Wrapper#prepare_request Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Prepares an HTTP request for KV value endpoints by adding the accept header for application/octet-stream and setting the content-type and body when a payload is present. ```APIDOC ## [Internal] Cloudflare::KV::Wrapper#prepare_request ### Description Prepares a request for KV value endpoints by setting headers and body for octet-stream content. ### Parameters - **request** (object) - The HTTP request object. - **payload** (object, optional) - The payload to send as the request body. ### Behavior - Adds `accept: application/octet-stream` header. - If payload is present, sets `content-type: application/octet-stream` and replaces the body with a buffered body containing `payload.to_s`. ``` -------------------------------- ### GET /zones/{id}/custom_hostnames/{cid} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Retrieves a specific custom hostname by ID. The response is lazy; the hostname data is fetched on first attribute access. ```APIDOC ## [GET] /zones/{id}/custom_hostnames/{cid} ### Description Retrieves a specific custom hostname by ID. The response is lazy; the hostname data is fetched on first attribute access. ### Method GET ### Endpoint /zones/{id}/custom_hostnames/{cid} ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID - **cid** (string) - Required - Custom hostname ID ### Response #### Success Response (200) - **result** (object) - CustomHostname object #### Response Example { "result": { "id": "hostname_id", "hostname": "custom.example.com", "ssl": { "method": "http", "type": "dv" } } } ``` -------------------------------- ### SSLAttribute#settings method Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/custom-hostname-ssl-attribute.md Returns a memoized Settings wrapper. If the settings key is absent, it initializes an empty hash on the source params, so writes through the Settings object are visible in to_h. ```ruby # Wraps the settings hash if it exists or initializes the settings hash and then wraps it def settings @settings ||= Settings.new(@params[:settings] ||= {}) end ``` -------------------------------- ### GET /zones/{id}/dns_records/{rid} Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Retrieves a specific DNS record by ID. The response is lazy; the record data is fetched on first attribute access. ```APIDOC ## [GET] /zones/{id}/dns_records/{rid} ### Description Retrieves a specific DNS record by ID. The response is lazy; the record data is fetched on first attribute access. ### Method GET ### Endpoint /zones/{id}/dns_records/{rid} ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID - **rid** (string) - Required - DNS record ID ### Response #### Success Response (200) - **result** (object) - DNS::Record object #### Response Example { "result": { "id": "record_id", "type": "A", "name": "example.com", "content": "192.0.2.1" } } ``` -------------------------------- ### Basic usage with email and key Source: https://github.com/socketry/cloudflare/blob/main/readme.md Connect to Cloudflare using email and API key, then interact with zones, DNS records, and firewall rules. Requires CLOUDFLARE_EMAIL and CLOUDFLARE_KEY environment variables. ```ruby require "cloudflare" # Grab some details from somewhere: email = ENV["CLOUDFLARE_EMAIL"] key = ENV["CLOUDFLARE_KEY"] Cloudflare.connect(key: key, email: email) do |connection| # Get all available zones: zones = connection.zones # Get a specific zone: zone = connection.zones.find_by_id("...") zone = connection.zones.find_by_name("example.com") # Get DNS records for a given zone: dns_records = zone.dns_records # Show some details of the DNS record: dns_record = dns_records.first puts dns_record.name # Add a DNS record. Here we add an A record for `batman.example.com`: zone = zones.find_by_name("example.com") zone.dns_records.create("A", "batman", "1.2.3.4", proxied: false) # Get firewall rules: all_rules = zone.firewall_rules # Block an ip: rule = zone.firewall_rules.set("block", "1.2.3.4", notes: "ssh dictionary attack") end ``` -------------------------------- ### GET /zones/{id}/dns_records Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/endpoints.md Lists DNS records for a zone with pagination and optional name filtering. Returns a paginated list of DNS::Record objects. ```APIDOC ## [GET] /zones/{id}/dns_records ### Description Lists DNS records for a zone with pagination and optional name filtering. Returns a paginated list of DNS::Record objects. ### Method GET ### Endpoint /zones/{id}/dns_records ### Parameters #### Path Parameters - **id** (string) - Required - Zone ID #### Query Parameters - **page** (integer) - Required - Page number for pagination - **per_page** (integer) - Required - Number of items per page - **name** (string) - Optional - Filter DNS records by name ### Response #### Success Response (200) - **result** (array) - Paginated list of DNS::Record objects #### Response Example { "result": [ { "id": "record_id", "type": "A", "name": "example.com", "content": "192.0.2.1" } ] } ``` -------------------------------- ### Create a new zone with Cloudflare::Zones#create Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/zones.md Posts a new zone to /zones/. Requires name and account (object responding to to_id). jump_start defaults to false. Returns the newly created Cloudflare::Zone with resource path advanced to /zones/{id}. ```ruby def create(name, account, jump_start: false, **options) payload = {name: name, account: account.to_id, jump_start: jump_start, **options} Zone.post(@resource, payload) do |resource, response| value = response.read result = value[:result] metadata = response.headers if id = result[:id] resource = resource.with(path: id) end Zone.new(resource, value: value, metadata: metadata) end end ``` -------------------------------- ### name accessor Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/dns.md Returns the record name, e.g. "www.example.com". ```ruby def name result[:name] end ``` -------------------------------- ### Namespace#keys method Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Returns a Keys collection bound to the namespace's keys endpoint. ```ruby def keys self.with(Keys, path: "keys") end ``` -------------------------------- ### Namespace#read_value method Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/kv.md Reads a value by key name, returning a binary string. ```ruby def read_value(name) value_representation(name).value end ``` -------------------------------- ### Pulling logs with iteration Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/logs.md Iterates over zone logs and prints each log's to_s. Also shows using Enumerable helpers to get the first 10 logs. ```ruby zone = connection.zones.find_by_name("example.com") zone.logs.each do |log| puts log.to_s end # Or with Enumerable helpers: recent = zone.logs.first(10).map(&:to_s) ``` -------------------------------- ### Require cloudflare/logs Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/logs.md Import path for the logs API. ```ruby require "cloudflare/logs" ``` -------------------------------- ### Require cloudflare/user Source: https://github.com/socketry/cloudflare/blob/main/_autodocs/api-reference/user.md Import path for the Cloudflare::User class. ```ruby require "cloudflare/user" ```