### Clone and Run LangChain Example (Bash) Source: https://developers.cloudflare.com/workers/languages/python/packages/langchain/index.md Use these commands to clone the example repository and start the LangChain application locally with `uv run pywrangler dev`. ```bash git clone https://github.com/cloudflare/python-workers-examples cd 05-langchain uv run pywrangler dev ``` -------------------------------- ### Basic Environment Variable Setup in .dev.vars or .env Source: https://developers.cloudflare.com/workers/local-development/environment-variables/index.md Example of common environment variables to define in `.dev.vars` or `.env` files for local development setup. ```ini API_HOST="localhost:3000" DEBUG="true" SECRET_TOKEN="my-local-secret-token" ``` -------------------------------- ### Quick Tunnel Output Example Source: https://developers.cloudflare.com/workers/wrangler/commands/tunnel Illustrates the expected output when a quick tunnel successfully starts, including the assigned temporary URL. ```text Starting quick tunnel to http://localhost:8080... Your tunnel URL: https://random-words-here.trycloudflare.com ``` -------------------------------- ### AI Agent Deploy Prompt Example Source: https://developers.cloudflare.com/workers/platform/claim-deployments/index.md An example prompt to guide an AI agent in creating and deploying a simple Cloudflare Worker using the Wrangler CLI. ```txt Make a very simple Hello World Cloudflare Worker in TypeScript and deploy it using the Wrangler CLI. Do not ask me questions. ``` -------------------------------- ### Example Output from Wrangler Local Development Server Source: https://developers.cloudflare.com/workers/tutorials/connect-to-turso-using-workers This output shows the console messages when Wrangler successfully starts a local server, including binding information and listening addresses. ```text Your worker has access to the following bindings: - Vars: - LIBSQL_DB_URL: "your-url" ⎔ Starting a local server... ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ [b] open a browser, [d] open Devtools, [l] turn off local mode, [c] clear console, [x] to exit │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ Debugger listening on ws://127.0.0.1:61918/1064babd-bc9d-4bed-b171-b35dab3b7680 For help, see: https://nodejs.org/en/docs/inspector Debugger attached. [mf:inf] Worker reloaded! (40.25KiB) [mf:inf] Listening on 0.0.0.0:8787 [mf:inf] - http://127.0.0.1:8787 [mf:inf] - http://192.168.1.136:8787 [mf:inf] Updated `Request.cf` object cache! ``` -------------------------------- ### Install Miniflare with bun Source: https://developers.cloudflare.com/workers/testing/miniflare/get-started Installs Miniflare as a development dependency using bun. ```bash bun add -d miniflare ``` -------------------------------- ### Example: Get a Secret with Output (npx) Source: https://developers.cloudflare.com/workers/wrangler/commands/secrets-store This example demonstrates retrieving a secret using `npx wrangler secrets-store secret get` with specific IDs and the `--remote` flag, followed by the expected tabular output. ```bash npx wrangler secrets-store secret get 8f7a1cdced6342c18d223ece462fd88d --secret-id 13bc7498c6374a4e9d13be091c3c65f1 --remote ``` ```text 🔐 Getting secret... (ID: 13bc7498c6374a4e9d13be091c3c65f1) ✓ Select an account: › My account | Name | ID | StoreID | Comment | Scopes | Status | Created | Modified | |-----------------------------|-------------------------------------|-------------------------------------|---------|---------|---------|------------------------|------------------------| | ServiceA_key-1 | 13bc7498c6374a4e9d13be091c3c65f1 | 8f7a1cdced6342c18d223ece462fd88d | | workers | active | 4/9/2025, 10:06:01 PM | 4/15/2025, 09:13:05 AM | ``` -------------------------------- ### Navigate to the project directory Source: https://developers.cloudflare.com/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.md Change into the newly created `finetune-chatgpt-model` directory to continue setup. ```sh cd finetune-chatgpt-model ``` -------------------------------- ### Initialize astro-blog-starter-template Source: https://developers.cloudflare.com/workers/get-started/quickstarts/index.md Start building a personal website, blog, or portfolio using Astro with this template. ```npm npm create cloudflare@latest -- --template=cloudflare/templates/astro-blog-starter-template ``` ```yarn yarn create cloudflare --template=cloudflare/templates/astro-blog-starter-template ``` ```pnpm pnpm create cloudflare@latest --template=cloudflare/templates/astro-blog-starter-template ``` -------------------------------- ### Clone Python Workers Examples Repository Source: https://developers.cloudflare.com/workers/languages/python Clones the official Cloudflare Python Workers examples repository and navigates into a specific example directory to explore various project setups. ```bash git clone https://github.com/cloudflare/python-workers-examples cd python-workers-examples/01-hello ``` -------------------------------- ### Set up a new Analog project with C3 Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/more-web-frameworks/analog Use the `create-cloudflare` CLI (C3) to initialize a new Analog project, which includes creating a directory and running Analog's official setup tool. ```npm npm create cloudflare@latest -- my-analog-app --framework=analog ``` ```yarn yarn create cloudflare my-analog-app --framework=analog ``` ```pnpm pnpm create cloudflare@latest my-analog-app --framework=analog ``` -------------------------------- ### Example: Get a Remote Secret with Specific IDs Source: https://developers.cloudflare.com/workers/wrangler/commands/secrets-store/index.md This example demonstrates retrieving a specific secret from a remote store using its store ID and secret ID. ```sh npx wrangler secrets-store secret get 8f7a1cdced6342c18d223ece462fd88d --secret-id 13bc7498c6374a4e9d13be091c3c65f1 --remote ``` -------------------------------- ### Initialize hello-world-do-template Project Source: https://developers.cloudflare.com/workers/get-started/quickstarts/index.md Create a basic 'Hello World' project using Durable Objects. ```Shell npm create cloudflare@latest -- --template=cloudflare/templates/hello-world-do-template ``` ```Shell yarn create cloudflare --template=cloudflare/templates/hello-world-do-template ``` ```Shell pnpm create cloudflare@latest --template=cloudflare/templates/hello-world-do-template ``` -------------------------------- ### Install Cloudflare Vite Plugin and Wrangler Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/tanstack-start/index.md Installs the necessary Cloudflare Vite plugin and Wrangler CLI as development dependencies for an existing TanStack Start application. ```shell npm i @cloudflare/vite-plugin wrangler -- -D ``` ```shell yarn add @cloudflare/vite-plugin wrangler -D ``` ```shell pnpm add @cloudflare/vite-plugin wrangler -D ``` ```shell bun add @cloudflare/vite-plugin wrangler -D ``` -------------------------------- ### Initialize d1-starter-sessions-api-template Project Source: https://developers.cloudflare.com/workers/get-started/quickstarts/index.md Set up a D1 starter template that utilizes the Sessions API for read replication. ```Shell npm create cloudflare@latest -- --template=cloudflare/templates/d1-starter-sessions-api-template ``` ```Shell yarn create cloudflare --template=cloudflare/templates/d1-starter-sessions-api-template ``` ```Shell pnpm create cloudflare@latest --template=cloudflare/templates/d1-starter-sessions-api-template ``` -------------------------------- ### Create remix-starter-template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Build a full-stack web application with Remix. Use the provided commands to quickly set up your project. ```shell npm create cloudflare@latest -- --template=cloudflare/templates/remix-starter-template ``` ```shell yarn create cloudflare --template=cloudflare/templates/remix-starter-template ``` ```shell pnpm create cloudflare@latest -- --template=cloudflare/templates/remix-starter-template ``` -------------------------------- ### Install Turso Client Library with npm Source: https://developers.cloudflare.com/workers/databases/third-party-integrations/turso/index.md Install the `@libsql/client` library using npm for connecting to Turso databases in your Worker. ```sh npm i @libsql/client ``` -------------------------------- ### Enable Static Prerendering in TanStack Start Vite Configuration Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/tanstack-start/index.md Configure your Vite project to enable static prerendering for a TanStack Start application. This setup uses the `@cloudflare/vite-plugin` and `@tanstack/react-start/plugin/vite`. ```javascript import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; import { tanstackStart } from "@tanstack/react-start/plugin/vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [ cloudflare({ viteEnvironment: { name: "ssr" } }), tanstackStart({ prerender: { enabled: true, }, }), react(), ], }); ``` ```typescript import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; import { tanstackStart } from "@tanstack/react-start/plugin/vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [ cloudflare({ viteEnvironment: { name: "ssr" } }), tanstackStart({ prerender: { enabled: true, }, }), react(), ], }); ``` -------------------------------- ### Use R2 Bucket in TanStack Start Server Function Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/tanstack-start/index.md Demonstrates how to interact with an R2 bucket (e.g., `put` and `get` objects) within a TanStack Start server function using the `env.MY_BUCKET` binding. ```js import { createServerFn } from "@tanstack/react-start"; import { env } from "cloudflare:workers"; const uploadFile = createServerFn({ method: "POST" }) .validator((data) => data) .handler(async ({ data }) => { await env.MY_BUCKET.put(data.key, data.content); return { success: true }; }); const getFile = createServerFn() .validator((key) => key) .handler(async ({ data: key }) => { const object = await env.MY_BUCKET.get(key); return object ? await object.text() : null; }); ``` ```ts import { createServerFn } from "@tanstack/react-start"; import { env } from "cloudflare:workers"; const uploadFile = createServerFn({ method: "POST" }) .validator((data: { key: string; content: string }) => data) .handler(async ({ data }) => { await env.MY_BUCKET.put(data.key, data.content); return { success: true }; }); const getFile = createServerFn() .validator((key: string) => key) .handler(async ({ data: key }) => { const object = await env.MY_BUCKET.get(key); return object ? await object.text() : null; }); ``` -------------------------------- ### Set up profile for Client B Source: https://developers.cloudflare.com/workers/wrangler/profiles Create a profile for a second client and bind it to their project directory, enabling easy switching between client contexts. ```bash wrangler auth create client-b ``` ```bash wrangler auth activate client-b ~/clients/client-b ``` -------------------------------- ### Proxy GET Requests to Another Site (JavaScript/TypeScript) Source: https://developers.cloudflare.com/workers/examples/respond-with-another-site Use these snippets to forward incoming GET requests to an external website, returning a 405 Method Not Allowed for other HTTP methods. These examples are designed for a Cloudflare Worker environment. ```JavaScript export default { async fetch(request) { function MethodNotAllowed(request) { return new Response(`Method ${request.method} not allowed.`, { status: 405, headers: { Allow: "GET", }, }); } // Only GET requests work with this proxy. if (request.method !== "GET") return MethodNotAllowed(request); return fetch(`https://example.com`); }, }; ``` ```TypeScript export default { async fetch(request): Promise { function MethodNotAllowed(request) { return new Response(`Method ${request.method} not allowed.`, { status: 405, headers: { Allow: "GET", }, }); } // Only GET requests work with this proxy. if (request.method !== "GET") return MethodNotAllowed(request); return fetch(`https://example.com`); }, } satisfies ExportedHandler; ``` -------------------------------- ### Create New Waku Project with C3 Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/more-web-frameworks/waku Initialize a new Waku project using the `create-cloudflare` CLI, specifying Waku as the framework. This sets up the project directory and initiates Waku's setup tool. ```npm npm create cloudflare@latest my-waku-app -- --framework=waku ``` ```yarn yarn create cloudflare@latest my-waku-app --framework=waku ``` ```pnpm pnpm create cloudflare@latest my-waku-app --framework=waku ``` -------------------------------- ### Set up profile for Client A Source: https://developers.cloudflare.com/workers/wrangler/profiles Create a profile for a specific client and bind it to their project directory for isolated access. ```bash wrangler auth create client-a ``` ```bash wrangler auth activate client-a ~/clients/client-a ``` -------------------------------- ### Get Miniflare Worker Instance Source: https://developers.cloudflare.com/workers/testing/miniflare/get-started/index.md Retrieve the underlying worker instance from Miniflare to interact with it directly, for example, to dispatch non-fetch events. ```js const worker = await mf.getWorker(); ``` -------------------------------- ### Turso Database Creation Output Example Source: https://developers.cloudflare.com/workers/databases/third-party-integrations/turso/index.md Example output showing the process and success message for creating a Turso database. ```sh # Example: Creating database my-db in Amsterdam, Netherlands (ams) # Once succeeded: Created database my-db in Amsterdam, Netherlands (ams) in 13 seconds. ``` -------------------------------- ### Install Turso Client Library with bun Source: https://developers.cloudflare.com/workers/databases/third-party-integrations/turso/index.md Install the `@libsql/client` library using bun for connecting to Turso databases in your Worker. ```sh bun add @libsql/client ``` -------------------------------- ### Create to-do-list-kv-template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Build a simple to-do list app with Cloudflare Workers Assets and Remix. Use these commands to get started. ```shell npm create cloudflare@latest -- --template=cloudflare/templates/to-do-list-kv-template ``` ```shell yarn create cloudflare --template=cloudflare/templates/to-do-list-kv-template ``` ```shell pnpm create cloudflare@latest -- --template=cloudflare/templates/to-do-list-kv-template ``` -------------------------------- ### Example JSON for build.started event Source: https://developers.cloudflare.com/workers/ci-cd/builds/event-subscriptions/index.md This JSON payload is triggered when a Workers build starts, providing details about the build process and its trigger. ```json { "type": "cf.workersBuilds.worker.build.started", "source": { "type": "workersBuilds.worker", "workerName": "my-worker" }, "payload": { "buildUuid": "build-12345678-90ab-cdef-1234-567890abcdef", "status": "running", "buildOutcome": null, "createdAt": "2025-05-01T02:48:57.132Z", "initializingAt": "2025-05-01T02:48:58.132Z", "runningAt": "2025-05-01T02:48:59.132Z", "stoppedAt": null, "buildTriggerMetadata": { "buildTriggerSource": "push_event", "branch": "main", "commitHash": "abc123def456", "commitMessage": "Fix bug in authentication", "author": "developer@example.com", "buildCommand": "npm run build", "deployCommand": "wrangler deploy", "rootDirectory": "/", "repoName": "my-worker-repo", "providerAccountName": "github-user", "providerType": "github" } }, "metadata": { "accountId": "f9f79265f388666de8122cfb508d7776", "eventSubscriptionId": "1830c4bb612e43c3af7f4cada31fbf3f", "eventSchemaVersion": 1, "eventTimestamp": "2025-05-01T02:48:57.132Z" } } ``` -------------------------------- ### Create Remix Starter Template Project Source: https://developers.cloudflare.com/workers/get-started/quickstarts/index.md Use these commands to initialize a new project based on the Remix Starter template, providing a foundation for building full-stack web applications with Remix. Choose your preferred package manager. ```npm npm create cloudflare@latest -- --template=cloudflare/templates/remix-starter-template ``` ```yarn yarn create cloudflare --template=cloudflare/templates/remix-starter-template ``` ```pnpm pnpm create cloudflare@latest --template=cloudflare/templates/remix-starter-template ``` -------------------------------- ### Accessing Bindings with `env` in Vitest Source: https://developers.cloudflare.com/workers/testing/vitest-integration/test-apis Use the `env` object to access bindings defined in your Vitest configuration. This example demonstrates putting and getting a value from a `KVNamespace` binding. ```javascript import { env } from "cloudflare:workers"; it("uses binding", async () => { await env.KV_NAMESPACE.put("key", "value"); expect(await env.KV_NAMESPACE.get("key")).toBe("value"); }); ``` -------------------------------- ### Basic Hono Application with Routes Source: https://developers.cloudflare.com/workers/tutorials/build-a-slackbot This snippet demonstrates a basic Hono application with GET and POST routes for '/posts', serving as a foundational example for structuring a web API. ```typescript import { Hono } from "hono"; const app = new Hono(); app.get("/posts", (c) => c.text("Posts!")); app.post("/posts", (c) => c.text("Created!", 201)); export default app; ``` -------------------------------- ### Initialize a new Qwik project with create-cloudflare Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/more-web-frameworks/qwik/index.md Use the `create-cloudflare` CLI to scaffold a new Qwik application, configuring it for deployment with Workers Assets. ```sh npm create cloudflare@latest -- my-qwik-app --framework=qwik ``` ```sh yarn create cloudflare my-qwik-app --framework=qwik ``` ```sh pnpm create cloudflare@latest my-qwik-app --framework=qwik ``` -------------------------------- ### Create react-router-starter-template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Build a full-stack web application with React Router 7. Use one of these commands to generate the starter template. ```shell npm create cloudflare@latest -- --template=cloudflare/templates/react-router-starter-template ``` ```shell yarn create cloudflare --template=cloudflare/templates/react-router-starter-template ``` ```shell pnpm create cloudflare@latest -- --template=cloudflare/templates/react-router-starter-template ``` -------------------------------- ### GET /env Source: https://developers.cloudflare.com/workers/languages/python/packages/fastapi/index.md This endpoint demonstrates how to access environment variables within a FastAPI application running on Cloudflare Workers. It returns a message including an example environment variable. ```APIDOC ## GET /env ### Description This endpoint demonstrates how to access environment variables within a FastAPI application running on Cloudflare Workers. It returns a message including an example environment variable. ### Method GET ### Endpoint /env ### Response #### Success Response (200) - **message** (string) - A message showing an environment variable. #### Response Example { "message": "Here is an example of getting an environment variable: [value of env.MESSAGE]" } ``` -------------------------------- ### Example Output for Get Worker Tag Source: https://developers.cloudflare.com/workers/ci-cd/builds/api-reference/index.md This JSON output illustrates the structure of the response when retrieving Worker tags, showing the worker's name and its associated tag. ```json { "name": "my-worker", "tag": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" } { "name": "another-worker", "tag": "8a1b2c3d4e5f67890abcdef123456789" } ``` -------------------------------- ### Initialize Prisma with a database Source: https://developers.cloudflare.com/workers/tutorials/using-prisma-postgres-with-workers Run the Prisma initialization command to set up Prisma ORM and connect to a new Prisma Postgres database instance. ```npm npx prisma@latest init --db ``` ```yarn yarn dlx prisma@latest init --db ``` ```pnpm pnpx prisma@latest init --db ``` -------------------------------- ### Running `wrangler tunnel quick-start` with `npx` Source: https://developers.cloudflare.com/workers/wrangler/commands/tunnel/index.md Execute the `quick-start` command via `npx` to expose a local server running on `http://localhost:8080`. ```sh npx wrangler tunnel quick-start http://localhost:8080 ``` -------------------------------- ### Default Multi-Module Worker in Cloudflare Workers Playground Source: https://developers.cloudflare.com/workers/playground This default Worker example demonstrates a multi-module setup, logging a message to the console, and returning an HTML response from an imported file. ```javascript import welcome from "welcome.html"; /** * @typedef {Object} Env */ export default { /** * @param {Request} request * @param {Env} env * @param {ExecutionContext} ctx * @returns {Response} */ fetch(request, env, ctx) { console.log("Hello Cloudflare Workers!"); return new Response(welcome, { headers: { "content-type": "text/html", }, }); }, }; ``` -------------------------------- ### Install Turso Client and Router Libraries Source: https://developers.cloudflare.com/workers/tutorials/connect-to-turso-using-workers/index.md Install the @libsql/client library for Turso database interaction and itty-router for request routing in your Worker project using your preferred package manager. ```bash npm i @libsql/client itty-router ``` ```bash yarn add @libsql/client itty-router ``` ```bash pnpm add @libsql/client itty-router ``` ```bash bun add @libsql/client itty-router ``` -------------------------------- ### Implement TracingChannel with AsyncLocalStorage (JavaScript) Source: https://developers.cloudflare.com/workers/runtime-apis/nodejs/diagnostics-channel/index.md This example shows how to create a `TracingChannel` and bind an `AsyncLocalStorage` store to its `start` event, allowing subscribers to access context during traced asynchronous operations. ```js import { tracingChannel } from "node:diagnostics_channel"; import { AsyncLocalStorage } from "node:async_hooks"; const channels = tracingChannel("my-channel"); const requestId = new AsyncLocalStorage(); channels.start.bindStore(requestId); alternate_channels.subscribe({ start(message) { console.log(requestId.getStore()); // { requestId: '123' } // Handle start message }, end(message) { console.log(requestId.getStore()); // { requestId: '123' } // Handle end message }, asyncStart(message) { console.log(requestId.getStore()); // { requestId: '123' } // Handle asyncStart message }, asyncEnd(message) { console.log(requestId.getStore()); // { requestId: '123' } // Handle asyncEnd message }, error(message) { console.log(requestId.getStore()); // { requestId: '123' } // Handle error message } }); // The subscriber handlers will be invoked while tracing the execution of the async // function passed into `channel.tracePromise`... channel.tracePromise( async () => { // Perform some asynchronous work... }, { requestId: "123" } ); ``` -------------------------------- ### Change directory to Analog project Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/more-web-frameworks/analog Navigate into the newly created Analog project directory after setup. ```shell cd my-analog-app ``` -------------------------------- ### Example Worker for CPU Profiling (JavaScript) Source: https://developers.cloudflare.com/workers/observability/dev-tools/cpu-usage/index.md This Worker demonstrates a simple setup with two functions that perform string concatenation, designed to illustrate CPU usage differences when profiled with DevTools. ```javascript const addNumbers = (body) => { for (let i = 0; i < 5000; ++i) { body = body + " " + i; } return body; }; const moreAddition = (body) => { for (let i = 5001; i < 15000; ++i) { body = body + " " + i; } return body; }; export default { async fetch(request, env, ctx) { let body = "Hello Profiler! - "; body = addNumbers(body); body = moreAddition(body); return new Response(body); }, }; ``` -------------------------------- ### Develop Analog project locally Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/more-web-frameworks/analog Run this command in your project directory to start a local server, allowing you to preview your Analog application during development. ```npm npm run dev ``` ```yarn yarn run dev ``` ```pnpm pnpm run dev ``` -------------------------------- ### Connect to PostgreSQL with Cloudflare Hyperdrive in TypeScript Source: https://developers.cloudflare.com/workers/get-started/prompting Connect to and query a Postgres database using Cloudflare Hyperdrive, utilizing the Postgres.js client. It includes configuration for Hyperdrive and instructions for installation and setup. ```typescript // Postgres.js 3.4.5 or later is recommended import postgres from "postgres"; export interface Env { // If you set another name in the Wrangler config file as the value for 'binding', // replace "HYPERDRIVE" with the variable name you defined. HYPERDRIVE: Hyperdrive; } export default { async fetch(request, env, ctx): Promise { console.log(JSON.stringify(env)); // Create a database client that connects to your database via Hyperdrive. // // Hyperdrive generates a unique connection string you can pass to // supported drivers, including node-postgres, Postgres.js, and the many // ORMs and query builders that use these drivers. const sql = postgres(env.HYPERDRIVE.connectionString) try { // Test query const results = await sql`SELECT * FROM pg_tables`; // Return result rows as JSON return Response.json(results); } catch (e) { console.error(e); return Response.json( { error: e instanceof Error ? e.message : e }, { status: 500 }, ); } }, } satisfies ExportedHandler; ``` ```json { "name": "hyperdrive-postgres", "main": "src/index.ts", "compatibility_date": "2025-02-11", "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "" } ] } ``` ```bash // Install Postgres.js npm install postgres // Create a Hyperdrive configuration npx wrangler hyperdrive create --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name" ``` -------------------------------- ### Clone and Run FastAPI Example Source: https://developers.cloudflare.com/workers/languages/python/packages/fastapi Use these commands to clone the `cloudflare/python-workers-examples` repository and run the FastAPI example locally for development. ```bash git clone https://github.com/cloudflare/python-workers-examples cd python-workers-examples/03-fastapi uv run pywrangler dev ``` -------------------------------- ### Retrieve All Members via cURL Source: https://developers.cloudflare.com/workers/tutorials/deploy-an-express-app/index.md Sends a GET request to fetch all members from the local API endpoint. The associated JSON block shows an example of the successful response containing a list of members. ```sh curl http://localhost:8787/api/members ``` ```json { "success": true, "members": [ { "id": 1, "name": "Alice Johnson", "email": "alice@example.com", "joined_date": "2024-01-15" }, { "id": 2, "name": "Bob Smith", "email": "bob@example.com", "joined_date": "2024-02-20" }, { "id": 3, "name": "Carol Williams", "email": "carol@example.com", "joined_date": "2024-03-10" } ] } ``` -------------------------------- ### FastAPI Application with Worker Entrypoint Source: https://developers.cloudflare.com/workers/languages/python/packages/fastapi This example demonstrates a complete FastAPI application integrated with a Cloudflare Worker entrypoint, showcasing basic GET, POST, and PUT endpoints, and how to access environment variables. ```python from workers import WorkerEntrypoint from fastapi import FastAPI, Request from pydantic import BaseModel import asgi class Default(WorkerEntrypoint): async def fetch(self, request): return await asgi.fetch(app, request, self.env) app = FastAPI() @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/env") async def root(req: Request): env = req.scope["env"] return {"message": "Here is an example of getting an environment variable: " + env.MESSAGE} class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.post("/items/") async def create_item(item: Item): return item @app.put("/items/{item_id}") async def create_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) return result @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} ``` -------------------------------- ### Install Turso Client Library with pnpm Source: https://developers.cloudflare.com/workers/databases/third-party-integrations/turso/index.md Install the `@libsql/client` library using pnpm for connecting to Turso databases in your Worker. ```sh pnpm add @libsql/client ``` -------------------------------- ### Initialize d1-template Project Source: https://developers.cloudflare.com/workers/get-started/quickstarts/index.md Create a new project for Cloudflare's native serverless SQL database, D1. ```Shell npm create cloudflare@latest -- --template=cloudflare/templates/d1-template ``` ```Shell yarn create cloudflare --template=cloudflare/templates/d1-template ``` ```Shell pnpm create cloudflare@latest --template=cloudflare/templates/d1-template ``` -------------------------------- ### Aggregate Concurrent GET Requests with Hono (Workers) Source: https://developers.cloudflare.com/workers/examples/aggregate-requests This example shows how to aggregate responses from multiple URLs using the Hono framework within a Cloudflare Worker, returning the combined JSON data. ```JavaScript import { Hono } from "hono"; const app = new Hono(); app.get("*", async (c) => { // someHost is set up to return JSON responses const someHost = "https://jsonplaceholder.typicode.com"; const url1 = someHost + "/todos/1"; const url2 = someHost + "/todos/2"; // Fetch both URLs concurrently const responses = await Promise.all([fetch(url1), fetch(url2)]); // Parse JSON responses concurrently const results = await Promise.all(responses.map((r) => r.json())); // Return aggregated results return c.json(results); }); export default app; ``` -------------------------------- ### JavaScript Examples for API Calls with and without CORS Proxy Source: https://developers.cloudflare.com/workers/examples/cors-header-proxy/index.md These JavaScript snippets, embedded in the demo HTML page, demonstrate making API calls. One example shows a direct call that fails due to CORS, while others use the Cloudflare Worker CORS proxy for successful GET and POST requests, including a preflight check. ```JavaScript let reqs = {}; reqs.noproxy = () => { return fetch("{api_url}").then(r => r.json()) } reqs.proxy = async () => { let href = "https://developers.cloudflare.com/workers/examples/cors-header-proxy/%7Bproxy_endpoint%7D?apiurl={api_url}" return fetch(window.location.origin + href).then(r => r.json()) } reqs.proxypreflight = async () => { let href = "https://developers.cloudflare.com/workers/examples/cors-header-proxy/%7Bproxy_endpoint%7D?apiurl={api_url}" let response = await fetch(window.location.origin + href, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ msg: "Hello world!" }) }) return response.json() } (async () => { for (const [reqName, req] of Object.entries(reqs)) { try { let data = await req() document.getElementById(reqName).innerHTML = JSON.stringify(data) } catch (e) { document.getElementById(reqName).innerHTML = e } } })() ``` -------------------------------- ### Example: Create a 'default' Secrets Store remotely Source: https://developers.cloudflare.com/workers/wrangler/commands/secrets-store/index.md This example demonstrates creating a Secrets Store named 'default' and executing the command against the remote Secrets Store. ```sh npx wrangler secrets-store store create default --remote ``` -------------------------------- ### Accessing Cloudflare Object in Python Worker Source: https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object This Python example for Cloudflare Workers shows how to access `request.cf` to get Cloudflare properties. It serializes the `cf` object to JSON or provides an error if it's missing. ```Python import json from workers import Response, WorkerEntrypoint from js import JSON class Default(WorkerEntrypoint): async def fetch(self, request): error = json.dumps({ "error": "The `cf` object is not available inside the preview." }) data = request.cf if request.cf is not None else error headers = {"content-type":"application/json"} return Response(JSON.stringify(data, None, 2), headers=headers) ``` -------------------------------- ### Create a new Cloudflare Worker project Source: https://developers.cloudflare.com/workers/tutorials/openai-function-calls-workers Initialize a new Cloudflare Worker project named 'openai-function-calling-workers' using npm, yarn, or pnpm. Select 'Hello World example', 'Worker only', and 'JavaScript' during setup. ```npm npm create cloudflare@latest -- openai-function-calling-workers ``` ```yarn yarn create cloudflare openai-function-calling-workers ``` ```pnpm pnpm create cloudflare@latest openai-function-calling-workers ```