### Wrangler Login Output Example Source: https://developers.cloudflare.com/workers/wrangler/commands/general Example output from the `wrangler login` command, indicating the OAuth process has started and a link has been opened in the browser. ```text ⛅️ wrangler 2.1.6 ------------------- Attempting to login via OAuth... Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?xyz... ``` -------------------------------- ### Hyperdrive Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Connect to a database using Hyperdrive. This example shows how to get a Hyperdrive connection. ```javascript export default { async fetch(request, env, ctx) { const connection = await env.MY_HYPERDRIVE.connect(); const [rows] = await connection.execute("SELECT 1"); connection.close(); return new Response(JSON.stringify(rows)); }, }; ``` -------------------------------- ### Cache API with `fetch` and `Response` Source: https://developers.cloudflare.com/workers/runtime-apis/cache A comprehensive example showing how to use `fetch` to get a response, then `cache.put` to store it, and finally `cache.match` to retrieve it. This pattern is common for implementing a cache-aside strategy. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const cache = caches.default; // Try to find the response in cache const cacheResponse = await cache.match(request); if (cacheResponse) { return cacheResponse; } // If not found, fetch from origin const fetchResponse = await fetch(request); // Clone the response to put in cache and return const responseToCache = fetchResponse.clone(); await cache.put(request, responseToCache); return fetchResponse; } ``` -------------------------------- ### Websocket Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Handle WebSocket connections. This example shows how to accept a WebSocket connection. ```javascript export default { async fetch(request, env, ctx) { if (request.headers.get("upgrade") === "websocket") { return env.MY_WEBSOCKET.handle(request); } return new Response("Hello World"); }, }; ``` -------------------------------- ### Basic R2 Download Example Source: https://developers.cloudflare.com/r2/api/workers/workers-api-usage Shows how to download a file from an R2 bucket. This example assumes the file exists and the Worker has read access to the bucket. ```javascript export default { async fetch(request, env, ctx) { const url = new URL(request.url); switch (url.pathname) { case "/download": if (request.method !== "GET") { return new Response("Method not allowed", { status: 405, }); } const fileName = url.searchParams.get("file"); if (!fileName) { return new Response("Missing file parameter", { status: 400, }); } const object = await env.YOUR_BUCKET_NAME.get(fileName); if (object === null) { return new Response("File not found", { status: 404, }); } const headers = new Headers(); object.writeHttpMetadata(headers); headers.set("etag", object.etag); return new Response(object.body, { headers, }); default: return new Response("Not Found", { status: 404, }); } }, }; ``` -------------------------------- ### Basic Worker Example Source: https://developers.cloudflare.com/workers/get-started/guide A simple "Hello, World!" example for a Cloudflare Worker. This demonstrates the basic structure of a Worker script. ```javascript export default { async fetch(request, env, ctx) { return new Response("Hello World!"); }, }; ``` -------------------------------- ### Example Video Transformation Source: https://developers.cloudflare.com/stream/transform-videos This example demonstrates sourcing an HD video from R2, shortening it, cropping it to a square, and removing audio, resulting in a 5-second MP4. ```URL https://example.com/cdn-cgi/media/mode=video,time=5s,duration=5s,width=500,height=500,fit=crop,audio=false/https://pub-8613b7f94d6146408add8fefb52c52e8.r2.dev/aus-mobile-demo.mp4 ``` -------------------------------- ### Install Wrangler using pnpm Source: https://developers.cloudflare.com/workers/wrangler/install-and-update If you prefer pnpm, you can use it to install Wrangler globally. Ensure pnpm is installed and configured. ```bash pnpm add -g @cloudflare/wrangler ``` -------------------------------- ### Example Image URL with Custom Domain Source: https://developers.cloudflare.com/images/optimization/hosted-images/serve-from-custom-domains An example of a complete image URL using a custom domain, demonstrating the structure with actual values. ```text https://example.com/cdn-cgi/imagedelivery/ZWd9g1K7eljCn_KDTu_MWA/083eb7b2-5392-4565-b69e-aff66acddd00/public ``` -------------------------------- ### Install Wrangler using yarn Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Alternatively, you can use yarn to install Wrangler globally. Make sure yarn is installed on your system. ```bash yarn global add @cloudflare/wrangler ``` -------------------------------- ### Install Wrangler with bun Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Install the latest version of Wrangler as a development dependency in your project using bun. ```bash bun add -d wrangler@latest ``` -------------------------------- ### Queue Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Send a message to a Cloudflare Queue. This example shows how to enqueue a message. ```javascript export default { async fetch(request, env, ctx) { await env.MY_QUEUE.send({ body: "my-message-body" }); return new Response("Message sent to queue"); }, }; ``` -------------------------------- ### Install Wrangler using npm Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Use npm to install Wrangler globally on your system. This is the recommended method for most users. ```bash npm install -g @cloudflare/wrangler ``` -------------------------------- ### Example Metadata Parameter Usage Source: https://developers.cloudflare.com/images/llms-full.txt This example shows how to use the `metadata` parameter to preserve copyright information, including Content Credentials, when transforming an image. Other metadata will be discarded. ```text metadata=copyright ``` -------------------------------- ### R2 Bucket Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Interact with an R2 bucket for object storage. This example shows how to put an object into the bucket. ```javascript export default { async fetch(request, env, ctx) { await env.MY_R2_BUCKET.put("my-object", "my-object-body"); return new Response("Object uploaded"); }, }; ``` -------------------------------- ### Create Image Variant - Go Example Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/subresources/variants/methods/create Example of how to create an image variant using Go. This code snippet shows how to construct and send the API request. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" "io/ioutil" ) func main() { accountId := "" imageId := "" apiToken := "" url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/images/v1/%s/variants", accountId, imageId) requestBody, err := json.Marshal(map[string]interface{}{ "name": "my-variant", "width": 100, "height": 100, "fit": "scale" }) if err != nil { fmt.Println("Error marshalling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer "+apiToken) req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Example Rate Limiting Rule Configuration Source: https://developers.cloudflare.com/waf/rate-limiting-rules This example shows how to configure a basic rate limiting rule to block requests that exceed 1000 per minute. ```json { "description": "Block requests that exceed 1000 per minute", "match": { "request": { "method": "*", "uri": "*", "headers": {}, "query": {}, "body": {} } }, "rate": { "period": 60, "requests_per_period": 1000 }, "action": { "type": "block" } } ``` -------------------------------- ### Cache Key Configuration Example Source: https://developers.cloudflare.com/cache/how-to/cache-keys This example demonstrates how to configure cache keys using Cloudflare's Cache Rules. It shows how to include specific headers and cookies while excluding others to precisely control caching. ```json { "name": "Cache Rule Example", "description": "Custom cache key configuration", "action": { "mode": "simulate", "cache_key": { "headers": { "include": [ "CF-Something", "CF-Another" ], "exclude": [ "Authorization" ] }, "cookies": { "include": [ "session_id" ], "exclude": [ "__cf_bm" ] }, "query_string": { "exclude_all": true } } }, "filter": { "expression": "(http.request.uri.path eq \"/images/logo.png\")" } } ``` -------------------------------- ### AI Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Interact with Cloudflare's AI services. This example shows how to use the `run` method to invoke an AI model. ```javascript export default { async fetch(request, env, ctx) { const response = await env.AI.run("@cf/meta/llama-2-7b-chat-fp16", { prompt: "Hello, world!" }); return new Response(JSON.stringify(response)); }, }; ``` -------------------------------- ### Vectorize Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Interact with a Vectorize index. This example shows how to insert a vector into the index. ```javascript export default { async fetch(request, env, ctx) { await env.MY_VECTORIZE_INDEX.insert([{ id: "vector-id-1", values: [0.1, 0.2, 0.3], metadata: { name: "vector-name-1" } }]); return new Response("Vector inserted"); }, }; ``` -------------------------------- ### Analytics Engine Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Send data to an Analytics Engine dataset. This example shows how to write data to a dataset. ```javascript export default { async fetch(request, env, ctx) { await env.MY_ANALYTICS_DATASET.writeDataPoint({ column1: "value1", column2: 100 }); return new Response("Data point written"); }, }; ``` -------------------------------- ### Create Image Variant - Python Example Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/subresources/variants/methods/create Example of how to create an image variant using Python. This demonstrates making a POST request to the Cloudflare API. ```python import requests account_id = '' image_id = '' api_token = '' url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1/{image_id}/variants" headers = { "Authorization": f"Bearer {api_token}", "Content-Type": "application/json" } data = { "name": "my-variant", "width": 100, "height": 100, "fit": "scale" } response = requests.post(url, headers=headers, json=data) print(response.json()) ``` -------------------------------- ### List Images V2 Response Example Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list This is an example of a successful 200 OK response when listing images. It includes details about errors, messages, and the list of images with their metadata and variants. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "continuation_token": "continuation_token", "images": [ { "id": "id", "creator": "107b9558-dd06-4bbd-5fef-9c2c16bb7900", "filename": "logo.png", "meta": { "key": "value" }, "requireSignedURLs": true, "uploaded": "2014-01-02T02:20:00.123Z", "variants": [ "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/thumbnail", "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/hero", "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/original" ] } ] }, "success": true } ``` -------------------------------- ### Module Worker Fetch Example Source: https://developers.cloudflare.com/workers/runtime-apis/fetch This example demonstrates making a fetch request within a Module Worker's scheduled event. Ensure fetch calls are within an async handler. ```javascript export default { async scheduled(controller, env, ctx) { return await fetch("https://example.com", { headers: { "X-Source": "Cloudflare-Workers", }, }); }, }; ``` -------------------------------- ### Durable Object Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Interact with a Durable Object. This example demonstrates how to get a Durable Object reference and call a method on it. ```javascript export default { async fetch(request, env, ctx) { const doId = env.MY_DO_NAMESPACE.idFromName("my-object-name"); const do = env.MY_DO_NAMESPACE.get(doId); const response = await do.fetch(request); return response; }, }; ``` -------------------------------- ### Navigate to the new project directory Source: https://developers.cloudflare.com/workers/get-started/guide Change the current directory to the newly created 'my-first-worker' project folder to begin development. ```bash cd my-first-worker ``` -------------------------------- ### KV Namespace Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Interact with a Cloudflare KV namespace to store and retrieve data. This example shows how to put and get a value. ```javascript export default { async fetch(request, env, ctx) { await env.MY_KV_NAMESPACE.put("mykey", "myvalue"); const value = await env.MY_KV_NAMESPACE.get("mykey"); return new Response(value); }, }; ``` -------------------------------- ### Basic Fetch Request Source: https://developers.cloudflare.com/workers/runtime-apis/fetch A simple example of making a GET request to a URL using the Fetch API. ```javascript async function fetchExample(request) { const url = 'https://example.com'; const response = await fetch(url); return new Response(response.body, { status: response.status, headers: response.headers }); } ``` -------------------------------- ### WebP Accept Header Example Source: https://developers.cloudflare.com/images/polish/compression This is an example of the Accept header that indicates browser support for WebP images. Polish uses this header to determine whether to serve WebP versions of images. ```http Accept: image/avif,image/webp,image/*,*/*;q=0.8 ``` -------------------------------- ### List Sites Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list Retrieves a list of all sites configured in your Magic Transit account. This endpoint is useful for getting an overview of your network setup. ```APIDOC ## GET /sites ### Description Retrieves a list of all sites configured in your Magic Transit account. ### Method GET ### Endpoint /sites ### Parameters None ### Request Example None ### Response #### Success Response (200) - **sites** (array) - A list of site objects. - **id** (string) - The unique identifier for the site. - **name** (string) - The name of the site. - **status** (string) - The current status of the site. #### Response Example { "sites": [ { "id": "f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6", "name": "Site A", "status": "active" }, { "id": "a1b2c3d4-e5f6-a7b8-c9d0-e1f2a3b4c5d6", "name": "Site B", "status": "inactive" } ] } ``` -------------------------------- ### Create Image Subresource (Go) Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Go example for creating an image subresource. This code demonstrates how to interact with the Cloudflare API using the Go SDK. ```Go import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" ) func main() { auth := cloudflare.APIKey("YOUR_API_KEY") client, err := cloudflare.NewWithAPIToken("YOUR_API_TOKEN") if err != nil { panic(err) } ctx := context.Background() subresource := cloudflare.ImageSubresource{ ID: cloudflare.String(""), Metadata: map[string]interface{}{"key": "value"}, } resp, err := client.CreateImageSubresource(ctx, "", "", subresource) if err != nil { panic(err) } fmt.Printf("%+v\n", resp) } ``` -------------------------------- ### Edit Image Variant - JavaScript SDK Example Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/subresources/variants/methods/edit This JavaScript code snippet shows how to use the Cloudflare SDK to edit an image variant. Ensure you have the SDK installed and configured with your account details. ```javascript import CloudflareClient from 'cloudflare'; const client = new CloudflareClient({ token: '', }); async function editImageVariant() { try { const response = await client.images.editImageVariant('', '', { width: 100, height: 100, fit: 'scale', quality: 80, }); console.log('Image variant updated:', response); } catch (error) { console.error('Error updating image variant:', error); } } editImageVariant(); ``` -------------------------------- ### Request Constructor Example Source: https://developers.cloudflare.com/workers/runtime-apis/request Demonstrates the basic syntax for creating a new Request object using the Request constructor. ```javascript let request = new Request(input, options) ``` -------------------------------- ### Create a preset Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/get Creates a new Realtime Kit preset. ```APIDOC ## POST /api/resources/realtime_kit/subresources/presets/methods/create ### Description Creates a new Realtime Kit preset. ### Method POST ### Endpoint /api/resources/realtime_kit/subresources/presets/methods/create ### Parameters #### Request Body - **name** (string) - Required - The name of the preset. ### Request Example { "name": "default_preset" } ### Response #### Success Response (200) - **preset** (object) - The newly created preset object. #### Response Example { "preset": { "id": "string", "name": "default_preset" } } ``` -------------------------------- ### Stream Data with TransformStream (Python) Source: https://developers.cloudflare.com/workers/runtime-apis/streams This Python example uses `TransformStream` to create a readable stream that enqueues data chunks with a delay. It demonstrates how to define a `start` function for the stream, which is then used to create a `ReadableStream`. ```python from workers import WorkerEntrypoint, Response from js import ReadableStream, TextEncoder from pyodide.ffi import create_proxy, to_js import asyncio class Default(WorkerEntrypoint): async def fetch(self, request): enc = TextEncoder.new() async def start(controller): for i in range(5): controller.enqueue(enc.encode(f"chunk {i}\n")) await asyncio.sleep(0.1) controller.close() stream = ReadableStream.new( to_js({"start": create_proxy(start)}) ) return Response(stream, headers={"Content-Type": "text/plain"}) ``` -------------------------------- ### R2 Bucket Operations (TypeScript) Source: https://developers.cloudflare.com/r2/api/workers/workers-api-usage Example of handling PUT, GET, and DELETE requests for R2 objects using TypeScript in a Module Worker. This snippet demonstrates interacting with the bound R2 bucket (`this.env.R2`). ```typescript import { WorkerEntrypoint } from "cloudflare:workers"; export default class extends WorkerEntrypoint { async fetch(request: Request) { const url = new URL(request.url); const key = url.pathname.slice(1); switch (request.method) { case "PUT": { await this.env.R2.put(key, request.body, { onlyIf: request.headers, httpMetadata: request.headers, }); return new Response(`Put ${key} successfully!`); } case "GET": { const object = await this.env.R2.get(key, { onlyIf: request.headers, range: request.headers, }); if (object === null) { return new Response("Object Not Found", { status: 404 }); } const headers = new Headers(); object.writeHttpMetadata(headers); headers.set("etag", object.httpEtag); // When no body is present, preconditions have failed return new Response("body" in object ? object.body : undefined, { status: "body" in object ? 200 : 412, headers, }); } case "DELETE": { await this.env.R2.delete(key); return new Response("Deleted!"); } default: return new Response("Method Not Allowed", { status: 405, headers: { Allow: "PUT, GET, DELETE", }, }); } } }; ``` -------------------------------- ### Python: Authorize R2 Bucket Requests Source: https://developers.cloudflare.com/r2/api/workers/workers-api-usage Implement authorization logic for R2 bucket operations in a Cloudflare Worker using Python. This example restricts PUT and DELETE requests with a custom header secret and GET requests to a specific file. ```python from workers import WorkerEntrypoint, Response from urllib.parse import urlparse ALLOW_LIST = ["cat-pic.jpg"] # Check requests for a pre-shared secretdef has_valid_header(request, env): return request.headers.get("X-Custom-Auth-Key") == env.AUTH_KEY_SECRET def authorize_request(request, env, key): if request.method in ["PUT", "DELETE"]: return has_valid_header(request, env) elif request.method == "GET": return key in ALLOW_LIST else: return False class Default(WorkerEntrypoint): async def fetch(self, request): url = urlparse(request.url) key = url.path[1:] if not authorize_request(self.env, key): return Response("Forbidden", status=403) # ... ``` -------------------------------- ### JavaScript: Authorize R2 Bucket Requests Source: https://developers.cloudflare.com/r2/api/workers/workers-api-usage Implement authorization logic for R2 bucket operations in a Cloudflare Worker. This example restricts PUT and DELETE requests using a custom header secret and GET requests to a specific file in an allow list. ```javascript const ALLOW_LIST = ["cat-pic.jpg"]; // Check requests for a pre-shared secretconst hasValidHeader = (request, env) => { return request.headers.get("X-Custom-Auth-Key") === env.AUTH_KEY_SECRET; }; function authorizeRequest(request, env, key) { switch (request.method) { case "PUT": case "DELETE": return hasValidHeader(request, env); case "GET": return ALLOW_LIST.includes(key); default: return false; } } export default { async fetch(request, env, ctx) { const url = new URL(request.url); const key = url.pathname.slice(1); if (!authorizeRequest(request, env, key)) { return new Response("Forbidden", { status: 403 }); } // ... }, }; ``` -------------------------------- ### Rewrite '/images' path to '/cdn-cgi/image/' Source: https://developers.cloudflare.com/images/optimization/transformations/rewrite-rules This example demonstrates a basic rewrite rule for Free and Pro plans. It rewrites requests starting with '/images' to use the Cloudflare Images transformation path, while ensuring the request is not already being handled by image resizing. ```Cloudflare Expression Language (starts_with(http.request.uri.path, "/images")) and (not (any(http.request.headers["via"][*] contains "image-resizing"))) ``` ```Cloudflare Expression Language concat("/cdn-cgi/image", substring(http.request.uri.path, 7)) ``` -------------------------------- ### Vitest Setup File Source: https://developers.cloudflare.com/workers/testing/vitest-integration Configure the testing environment in `vitest/setup.ts`. This file is executed before each test suite. ```typescript import { beforeAll, afterAll } from "vitest"; import "@cloudflare/vitest-environment-miniflare"; // Mock the global fetch for tests // beforeAll(() => { // global.fetch = fetch; // }); // afterAll(() => { // // Clean up mocks if necessary // }); ``` -------------------------------- ### Example of Optimized Image URL with Flexible Variants Source: https://developers.cloudflare.com/images/llms-full.txt Once flexible variants are enabled, you can use optimization parameters like width and sharpening directly in the image URL. This example shows how to set the width to 400 pixels and apply a sharpening of 3. ```url https://imagedelivery.net/{account_hash}/{image_id}/w=400,sharpen=3 ``` -------------------------------- ### Start Tail Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/subresources/variants/methods/edit Starts a new tail for a Worker. ```APIDOC ## POST /api/resources/workers/subresources/scripts/subresources/tail/methods/create ### Description Starts a tail. ### Method POST ### Endpoint /api/resources/workers/subresources/scripts/subresources/tail/methods/create ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/profiles/subresources/custom/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get a custom DLP profile. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/profiles/subresources/custom/methods/get ### Description Get a custom DLP profile. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/profiles/subresources/custom/methods/get ### Parameters #### Query Parameters - **profile_id** (string) - Required - The ID of the custom DLP profile. ### Response #### Success Response (200) - **profile** (object) - The details of the custom DLP profile. - **id** (string) - The profile ID. - **name** (string) - The profile name. - **rules** (array) - List of rules associated with the profile. #### Response Example { "profile": { "id": "profile-xyz", "name": "Custom Financial Data", "rules": [ { "name": "Account Number", "pattern": "\\b[A-Z]{2}\\d{8}\\b" } ] } } ``` -------------------------------- ### Passthrough Compressed Data with Fetch Source: https://developers.cloudflare.com/workers/runtime-apis/fetch This example demonstrates how to fetch a resource and return its response, preserving the original compression. It sets the 'Accept-Encoding' header to 'br, gzip' to indicate support for Brotli or Gzip compression. The response body and headers are directly returned, allowing compressed data to pass through without recompression, which is useful for origin servers or compressed media assets. ```typescript export default { async fetch(request) { // Accept brotli or gzip compression const headers = new Headers({ "Accept-Encoding": "br, gzip", }); let response = await fetch("https://developers.cloudflare.com", { method: "GET", headers, }); // As long as the original response body is returned and the Content-Encoding header is // preserved, the same encoded data will be returned without needing to be compressed again. return new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers, }); }, }; ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/profiles/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get a specific DLP profile. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/profiles/methods/get ### Description Get a specific DLP profile. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/profiles/methods/get ### Parameters #### Query Parameters - **profile_id** (string) - Required - The ID of the DLP profile. ### Response #### Success Response (200) - **profile** (object) - The details of the DLP profile. - **id** (string) - The profile ID. - **name** (string) - The profile name. - **type** (string) - The profile type (e.g., "predefined", "custom"). - **rules** (array) - List of rules associated with the profile. #### Response Example { "profile": { "id": "profile-abc", "name": "PII Data", "type": "predefined", "rules": [ { "name": "Social Security Number", "pattern": "\\d{3}-\\d{2}-\\d{4}" } ] } } ``` -------------------------------- ### List Images with Pagination Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list This example shows how to list images with pagination parameters, allowing you to retrieve images in batches. It includes parameters for limit and offset. ```javascript import { CloudflareImages } from "@cloudflare/images"; const images = new CloudflareImages({ accountId: "YOUR_ACCOUNT_ID", apiKey: "YOUR_API_KEY", }); async function listImagesPaginated() { try { const response = await images.list({ limit: 10, // Number of images to retrieve per page offset: 0, // Starting point for retrieval }); console.log(response.data); } catch (error) { console.error("Error listing images with pagination:", error); } } listImagesPaginated(); ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/rules/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get an email scanner rule. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/rules/methods/get ### Description Get an email scanner rule. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/rules/methods/get ### Parameters #### Query Parameters - **rule_id** (string) - Required - The ID of the email scanner rule. ### Response #### Success Response (200) - **rule** (object) - The details of the email scanner rule. - **id** (string) - The rule ID. - **name** (string) - The rule name. - **pattern** (string) - The regex pattern. - **action** (string) - The action to take (e.g., "block", "alert"). #### Response Example { "rule": { "id": "rule-123", "name": "Credit Card Numbers", "pattern": "\\d{4}-\\d{4}-\\d{4}-\\d{4}", "action": "block" } } ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/settings/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get DLP account-level settings. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/settings/methods/get ### Description Get DLP account-level settings. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/settings/methods/get ### Response #### Success Response (200) - **settings** (object) - The current DLP account-level settings. - **sensitive_data_detection** (boolean) - Whether sensitive data detection is enabled. - **allowed_countries** (array) - List of allowed countries for data processing. #### Response Example { "settings": { "sensitive_data_detection": true, "allowed_countries": ["US", "CA"] } } ``` -------------------------------- ### Create App Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/get Creates a new Realtime Kit application. ```APIDOC ## POST /api/resources/realtime_kit/subresources/apps/methods/post ### Description Creates a new Realtime Kit application. ### Method POST ### Endpoint /api/resources/realtime_kit/subresources/apps/methods/post ### Parameters #### Request Body - **name** (string) - Required - The name of the application. ### Request Example { "name": "my_new_app" } ### Response #### Success Response (200) - **app** (object) - The newly created application object. #### Response Example { "app": { "id": "string", "name": "my_new_app" } } ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/payload_logs/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get payload log settings. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/payload_logs/methods/get ### Description Get payload log settings. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/payload_logs/methods/get ### Response #### Success Response (200) - **enabled** (boolean) - Whether payload logging is enabled. - **log_type** (string) - The type of logs being collected (e.g., "all", "sensitive_only"). #### Response Example { "enabled": true, "log_type": "sensitive_only" } ``` -------------------------------- ### Start Tail Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Starts a tail connection for a Cloudflare Worker. ```APIDOC ## POST /api/resources/workers/subresources/scripts/subresources/tail/methods/create ### Description Starts a tail for a Worker. ### Method POST ### Endpoint /api/resources/workers/subresources/scripts/subresources/tail/methods/create ``` -------------------------------- ### GET /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/account_mapping/methods/get Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/create Get account mapping for email scanning. ```APIDOC ## GET /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/account_mapping/methods/get ### Description Get account mapping for email scanning. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/dlp/subresources/email/subresources/account_mapping/methods/get ### Response #### Success Response (200) - **mapping** (object) - The account mapping configuration. - **cloud_account_id** (string) - The Cloudflare account ID. - **email_service_provider** (string) - The email service provider (e.g., "gmail", "outlook"). - **api_key** (string) - The API key for the email service provider. #### Response Example { "mapping": { "cloud_account_id": "12345abcde", "email_service_provider": "gmail", "api_key": "********************" } } ``` -------------------------------- ### Enable Client Hints via HTTP Response Headers Source: https://developers.cloudflare.com/images/llms-full.txt Include these headers in your HTML response to enable client hints for responsive images. ```HTTP critical-ch: sec-ch-viewport-width, sec-ch-dpr permissions-policy: ch-dpr=({ZONE}), ch-viewport-width=({ZONE}) ``` -------------------------------- ### Get Token Validation Configuration Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list Get a single Token Configuration. ```APIDOC ## GET /api/resources/token_validation/subresources/configuration/methods/get ### Description Get a single Token Configuration. ### Method GET ### Endpoint /api/resources/token_validation/subresources/configuration/methods/get ``` -------------------------------- ### Browser Binding Example Source: https://developers.cloudflare.com/workers/runtime-apis/bindings Access browser-specific APIs from your Worker. This example shows how to use `navigator.userAgent`. ```javascript export default { async fetch(request, env, ctx) { const userAgent = env.navigator.userAgent; return new Response(userAgent); }, }; ``` -------------------------------- ### Rate Limiting Rule with Different Actions Source: https://developers.cloudflare.com/waf/rate-limiting-rules This example shows how to use different actions like 'log' or 'throttle' in rate limiting rules. ```json { "description": "Log requests exceeding 5000 per minute, throttle requests exceeding 10000 per minute", "match": { "request": { "method": "*", "uri": "*", "headers": {}, "query": {}, "body": {} } }, "rate": { "period": 60, "requests_per_period": 5000 }, "action": { "type": "log" } }, { "description": "Throttle requests exceeding 10000 per minute", "match": { "request": { "method": "*", "uri": "*", "headers": {}, "query": {}, "body": {} } }, "rate": { "period": 60, "requests_per_period": 10000 }, "action": { "type": "throttle", "duration": 300 } } ``` -------------------------------- ### Cache Match with Options Source: https://developers.cloudflare.com/workers/runtime-apis/cache Shows how to use cache.match() with options to control cache behavior, such as ignoring search parameters. This allows for more flexible cache retrieval. ```javascript const cache = await caches.open('my-cache-name'); const response = await cache.match('https://example.com/data?ignore=this', { ignoreSearch: true }); ``` -------------------------------- ### Transform Video Example Source: https://developers.cloudflare.com/stream/transform-videos This example shows how to use the Cloudflare API to transform a video. You can specify parameters like width, height, and quality to modify the video output. This is useful for creating different versions of a video for various platforms or use cases. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//stream/transformations/" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ "width": 1280, "height": 720, "quality": 80 }' ``` -------------------------------- ### Install Wrangler with pnpm Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Install the latest version of Wrangler as a development dependency in your project using pnpm. ```bash pnpm add -D wrangler@latest ``` -------------------------------- ### Install Wrangler with yarn Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Install the latest version of Wrangler as a development dependency in your project using yarn. ```bash yarn add -D wrangler@latest ``` -------------------------------- ### List Images V2 Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list This example shows how to list all images in your account using a cURL command. ```APIDOC ## GET /accounts/:account_id/images/v2 ### Description Retrieves a list of images uploaded to your Cloudflare Images account. This endpoint supports pagination using a continuation token. ### Method GET ### Endpoint `/accounts/:account_id/images/v2` ### Parameters #### Path Parameters - **account_id** (string) - Required - Your Cloudflare account ID. #### Query Parameters - **continuation_token** (string) - Optional - A token to retrieve the next page of results. ### Request Example ```bash curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/images/v2 \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" ``` ### Response #### Success Response (200) - **result** (object) - Contains the list of images and pagination information. - **continuation_token** (string) - A token to retrieve the next page of results. - **images** (array) - An array of image objects. - **id** (string) - The unique identifier for the image. - **creator** (string) - The ID of the user or service that uploaded the image. - **filename** (string) - The original filename of the image. - **meta** (object) - A key-value object containing metadata for the image. - **requireSignedURLs** (boolean) - Indicates if signed URLs are required for accessing the image variants. - **uploaded** (string) - The timestamp when the image was uploaded (ISO 8601 format). - **variants** (array) - An array of URLs for different variants of the image. #### Response Example ```json { "errors": [], "messages": [], "result": { "continuation_token": "continuation_token", "images": [ { "id": "id", "creator": "107b9558-dd06-4bbd-5fef-9c2c16bb7900", "filename": "logo.png", "meta": { "key": "value" }, "requireSignedURLs": true, "uploaded": "2014-01-02T02:20:00.123Z", "variants": [ "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/thumbnail", "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/hero", "https://imagedelivery.net/MTt4OTd0b0w5aj/107b9558-dd06-4bbd-5fef-9c2c16bb7900/original" ] } ] }, "success": true } ``` ``` -------------------------------- ### Install Wrangler with npm Source: https://developers.cloudflare.com/workers/wrangler/install-and-update Install the latest version of Wrangler as a development dependency in your project using npm. ```bash npm i -D wrangler@latest ``` -------------------------------- ### Create Manual Build Source: https://developers.cloudflare.com/api/resources/images/subresources/v2/methods/list Initiates a manual build process for a worker. ```APIDOC ## POST /api/resources/workers_builds/subresources/triggers/methods/create_build ### Description Creates a manual build for a worker. ### Method POST ### Endpoint /api/resources/workers_builds/subresources/triggers/methods/create_build ### Parameters #### Request Body - **script_name** (string) - Required - The name of the script to build. - **ref** (string) - Required - The Git reference (branch or tag) to build. - **sha** (string) - Optional - The Git commit SHA to build. ### Request Example { "script_name": "my-worker", "ref": "main", "sha": "a1b2c3d4e5f6" } ### Response #### Success Response (200) - **build_id** (string) - The ID of the created build. #### Response Example { "build_id": "123e4567-e89b-12d3-a456-426614174000" } ``` -------------------------------- ### Get Images Subresources v1 Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/methods/get Retrieves details about images subresources. This is a GET request to the specified endpoint. ```APIDOC ## GET /api/resources/images/subresources/v1 ### Description Retrieves details about images subresources. ### Method GET ### Endpoint /api/resources/images/subresources/v1 ### Parameters #### Path Parameters None #### Query Parameters None ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example { "example": "response body" } ``` -------------------------------- ### Generate Image with Stable Diffusion XL Lightning (1-step) Source: https://developers.cloudflare.com/workers-ai/models/stable-diffusion-xl-lightning This example demonstrates the fastest image generation with the 1-step version of Stable Diffusion XL Lightning. Use this when absolute speed is the top priority. ```javascript import { Ai } from "@cloudflare/ai"; export default { async fetch(request, env) { const prompt = "A photo of an astronaut riding a horse on the moon"; const ai = new Ai(env.AI); const response = await ai.generateImage( "@cf/runwayml/stable-diffusion-xl-lightning-1step", prompt ); return new Response(response, { headers: { "content-type": "image/png", }, }); }, }; ``` -------------------------------- ### Create a Bookmark application Source: https://developers.cloudflare.com/api/resources/images/subresources/v1/subresources/variants/methods/edit Creates a new Bookmark application. ```APIDOC ## POST /api/resources/zero_trust/subresources/access/subresources/bookmarks/methods/create ### Description Creates a new Bookmark application. ### Method POST ### Endpoint /api/resources/zero_trust/subresources/access/subresources/bookmarks/methods/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None explicitly defined in the source. ### Request Example ```json { "example": "No request body example provided in source." } ``` ### Response #### Success Response (200) None explicitly defined in the source. #### Response Example ```json { "example": "No response example provided in source." } ``` ``` -------------------------------- ### Get Image Bytes Source: https://developers.cloudflare.com/images/storage/binding Gets the raw bytes of a specific hosted image. Returns a ReadableStream or null if the image does not exist. ```APIDOC ## GET /images/v1/{imageId}/blob ### Description Gets the raw bytes of an image. Returns `ReadableStream` or `null` if no image with the given ID exists. This streams the original uploaded file. ### Method GET ### Endpoint /images/v1/{imageId}/blob ### Parameters #### Path Parameters - **imageId** (string) - Required - The ID of the image (UUID or custom ID). ### Response #### Success Response (200) - **ReadableStream** - A stream of the image's raw bytes. #### Response Example (Response will be a stream of bytes, not a JSON object. Example shown is conceptual.) ``` [Binary Image Data Stream] ``` ```