TITLE: Long-Running Task API Implementation DESCRIPTION: API route implementation for handling long-running background tasks with request verification. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_6 LANGUAGE: typescript CODE: import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" async function handler(request: Request) { const data = await request.json() for (let i = 0; i < 10; i++) { await fetch("https://firstqstashmessage.requestcatcher.com/test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, }) await new Promise((resolve) => setTimeout(resolve, 500)) } return Response.json({ success: true }) } export const POST = verifySignatureAppRouter(handler) ---------------------------------------- TITLE: JWT Header Structure for Upstash-Signature DESCRIPTION: Shows the structure of the JWT header used in the Upstash-Signature for request signing. It specifies the algorithm (HS256) and token type (JWT). SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/security.mdx#2025-04-05_snippet_1 LANGUAGE: json CODE: { "alg": "HS256", "typ": "JWT" } ---------------------------------------- TITLE: Publishing QStash Message Using Node.js DESCRIPTION: Example of publishing a message to QStash using Node.js fetch API, including headers for authentication and message configuration. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/publish.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch( "https://qstash.upstash.io/v2/publish/https://www.example.com", { method: "POST", headers: { Authorization: "Bearer ", "Content-Type": "application/json", "Upstash-Method": "POST", "Upstash-Delay": "10s", "Upstash-Retries": "3", "Upstash-Forward-Custom-Header": "custom-value", }, body: JSON.stringify({ message: "Hello, World!", }), } ); ---------------------------------------- TITLE: Initializing QStash Client in TypeScript DESCRIPTION: Basic setup for creating a QStash client instance using a token. This is the initial step for interacting with QStash services. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/gettingstarted.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "", }); ---------------------------------------- TITLE: Publishing QStash Message Using cURL DESCRIPTION: Example of publishing a message to QStash using cURL, demonstrating usage of custom headers for delay, retries, and forwarding. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/publish.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST "https://qstash.upstash.io/v2/publish/https://www.example.com" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -H "Upstash-Method: POST" \ -H "Upstash-Delay: 10s" \ -H "Upstash-Retries: 3" \ -H "Upstash-Forward-Custom-Header: custom-value" \ -d '{"message":"Hello, World!"}' ---------------------------------------- TITLE: Initializing Asynchronous QStash Client DESCRIPTION: Setup and initialization of an asynchronous QStash client using asyncio for asynchronous operations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/gettingstarted.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import asyncio from qstash import AsyncQStash async def main(): client = AsyncQStash("") await client.message.publish_json(...) asyncio.run(main()) ---------------------------------------- TITLE: Publishing QStash Message Using Go DESCRIPTION: Example of publishing a message to QStash using Go's HTTP client, demonstrating request creation and header setting. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/publish.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: var data = strings.NewReader(`{"message":"Hello, World!"}`) req, err := http.NewRequest("POST", "https://qstash.upstash.io/v2/publish/https://www.example.com", data) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") req.Header.Set("Upstash-Method", "POST") req.Header.Set("Upstash-Delay", "10s") req.Header.Set("Upstash-Retries", "3") req.Header.Set("Upstash-Forward-Custom-Header", "custom-value") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: QStash Integration Implementation DESCRIPTION: Complete TypeScript implementation of QStash webhook handling in a Cloudflare Worker, including signature verification and request processing. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: import { Receiver } from "@upstash/qstash"; export interface Env { QSTASH_CURRENT_SIGNING_KEY: string; QSTASH_NEXT_SIGNING_KEY: string; } export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { const c = new Receiver({ currentSigningKey: env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: env.QSTASH_NEXT_SIGNING_KEY, }); const body = await request.text(); const isValid = await c .verify({ signature: request.headers.get("Upstash-Signature")!, body, }) .catch((err) => { console.error(err); return false; }); if (!isValid) { return new Response("Invalid signature", { status: 401 }); } console.log("The signature was valid"); // do work here return new Response("Hello World!"); }, }; ---------------------------------------- TITLE: Implementing JWT Verification for QStash Webhook in Go DESCRIPTION: Verifies the JWT token from the QStash webhook, including checks for issuer, expiration, and body hash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/fly-io/go.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: func verify(body []byte, tokenString, signingKey string) error { token, err := jwt.Parse( tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return []byte(signingKey), nil }) if err != nil { return err } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { return fmt.Errorf("Invalid token") } if !claims.VerifyIssuer("Upstash", true) { return fmt.Errorf("invalid issuer") } if !claims.VerifyExpiresAt(time.Now().Unix(), true) { return fmt.Errorf("token has expired") } if !claims.VerifyNotBefore(time.Now().Unix(), true) { return fmt.Errorf("token is not valid yet") } bodyHash := sha256.Sum256(body) if claims["body"] != base64.URLEncoding.EncodeToString(bodyHash[:]) { return fmt.Errorf("body hash does not match") } return nil } ---------------------------------------- TITLE: Publishing a Message with Custom Headers using cURL DESCRIPTION: This snippet demonstrates how to publish a message to QStash using cURL, including a custom header and JSON payload. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H 'Upstash-Forward-My-Header: my-value' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' ---------------------------------------- TITLE: Publishing with Content-Based Deduplication in QStash TypeScript DESCRIPTION: This snippet shows how to publish a message with content-based deduplication enabled using the QStash client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/publish.mdx#2025-04-05_snippet_5 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, contentBasedDeduplication: true, }); ---------------------------------------- TITLE: Verifying QStash Signatures using TypeScript SDK DESCRIPTION: Example of using the QStash TypeScript SDK to verify request signatures using the Receiver class with current and next signing keys. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/signature.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Receiver } from "@upstash/qstash"; const receiver = new Receiver({ currentSigningKey: "YOUR_CURRENT_SIGNING_KEY", nextSigningKey: "YOUR_NEXT_SIGNING_KEY", }); // ... in your request handler const signature = req.headers["Upstash-Signature"]; const body = req.body; const isValid = receiver.verify({ body, signature, url: "YOUR-SITE-URL", }); ---------------------------------------- TITLE: Implementing QStash Message Receiver in Python DESCRIPTION: Demonstrates how to initialize and use the QStash Receiver class to verify incoming message signatures. Requires the QStash Python SDK and valid signing keys for authentication. The verification process checks the message body against the provided signature and URL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/receiver.mdx#2025-04-05_snippet_0 LANGUAGE: python CODE: from qstash import Receiver receiver = Receiver( current_signing_key="YOUR_CURRENT_SIGNING_KEY", next_signing_key="YOUR_NEXT_SIGNING_KEY", ) # ... in your request handler signature, body = req.headers["Upstash-Signature"], req.body receiver.verify( body=body, signature=signature, url="YOUR-SITE-URL", ) ---------------------------------------- TITLE: Publishing a JSON Message with Custom Headers using TypeScript DESCRIPTION: This snippet shows how to publish a JSON message to QStash using the TypeScript client, including a custom header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://example.com", body: { "hello": "world" }, headers: { "my-header": "my-value" }, }); ---------------------------------------- TITLE: Manual QStash Webhook Verification Handler DESCRIPTION: Implementation of Lambda handler with manual webhook verification logic. Includes signature verification and JWT validation. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/nodejs.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: import type { APIGatewayEvent, APIGatewayProxyResult } from "aws-lambda" import { createHash, createHmac } from "node:crypto" export const handler = async ( event: APIGatewayEvent, ): Promise => { const signature = event.headers["upstash-signature"] ?? "" const currentSigningKey = process.env.QSTASH_CURRENT_SIGNING_KEY ?? "" const nextSigningKey = process.env.QSTASH_NEXT_SIGNING_KEY ?? "" const url = `https://${event.requestContext.domainName}` try { await verify(signature, currentSigningKey, event.body, url).catch((err) => { console.error( `Failed to verify signature with current signing key: ${err}` ) return verify(signature, nextSigningKey, event.body, url) }) } catch (err) { const message = err instanceof Error ? err.toString() : err return { statusCode: 400, body: JSON.stringify({ error: message }), } } return { statusCode: 200, body: JSON.stringify({ message: "Request processed successfully" }), } } ---------------------------------------- TITLE: JWT Payload Structure for Upstash-Signature DESCRIPTION: Illustrates the payload structure of the JWT used in the Upstash-Signature. It includes various claims such as issuer, subject, expiration time, and a hash of the request body. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/security.mdx#2025-04-05_snippet_2 LANGUAGE: json CODE: { "iss": "Upstash", "sub": "https://qstash-remote.requestcatcher.com/test", "exp": 1656580612, "nbf": 1656580312, "iat": 1656580312, "jti": "jwt_67kxXD6UBAk7DqU6hzuHMDdXFXfP", "body": "qK78N0k3pNKI8zN62Fq2Gm-_LtWkJk1z9ykio3zZvY4=" } ---------------------------------------- TITLE: Publishing a JSON Message with Custom Headers using Python DESCRIPTION: This snippet demonstrates how to publish a JSON message to QStash using the Python client, including a custom header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "my-header": "my-value", }, ) ---------------------------------------- TITLE: Publishing to a URL Group using Python DESCRIPTION: This snippet shows how to publish a JSON message to a URL group in QStash using the Python client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_5 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url_group="my-url-group", body={ "hello": "world", }, ) ---------------------------------------- TITLE: Combining RatePerSecond and Parallelism in QStash DESCRIPTION: Demonstrates how to combine both rate limiting and parallelism controls with values of 20 calls per second and 10 parallel executions. Shows implementation in TypeScript and cURL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/flowcontrol.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", ratePerSecond: 20, parallelism: 10 }, }); LANGUAGE: bash CODE: curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:Rate=20,Parallelism=10" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ---------------------------------------- TITLE: Publishing to a URL Group using cURL DESCRIPTION: This snippet shows how to publish a message to a URL group in QStash using cURL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_3 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/my-url-group' ---------------------------------------- TITLE: Configuring Retries for QStash Publishing in TypeScript DESCRIPTION: This snippet shows how to configure the number of retries when publishing a message using the QStash client. The maximum number of retries depends on the QStash plan. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/publish.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, retries: 1, }); ---------------------------------------- TITLE: Batching Messages with URL Groups in QStash DESCRIPTION: Shows how to batch send messages using URL Groups in QStash. This method allows sending to predefined groups of URLs alongside individual destinations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/batch.mdx#2025-04-05_snippet_1 LANGUAGE: shell CODE: curl -XPOST https://qstash.upstash.io/v2/batch \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d ' [ { "destination": "myUrlGroup" }, { "destination": "https://example.com/destination2" } ]' LANGUAGE: typescript CODE: const client = new Client({ token: "" }); // Each message is the same as the one you would send with the publish endpoint const res = await client.batchJSON([ { urlGroup: "myUrlGroup", }, { url: "https://example.com/destination2", }, ]); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.batch_json( [ {"url_group": "my-url-group"}, {"url": "https://example.com/destination2"}, ] ) ---------------------------------------- TITLE: Publishing to URL with Delay and Headers in TypeScript DESCRIPTION: This snippet demonstrates how to publish a JSON message to a URL using the QStash client, including a 3-second delay and custom headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/publish.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, headers: { "test-header": "test-value" }, delay: "3s", }); ---------------------------------------- TITLE: Bulk Cancellation of QStash Messages in TypeScript DESCRIPTION: This snippet illustrates how to cancel multiple messages at once or cancel all messages in QStash. It demonstrates both deleting specific messages by their IDs and deleting all messages. Requires the @upstash/qstash client and a valid token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/messages.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // deleting two messages at once await client.messages.deleteMany([ "message-id-1", "message-id-2", ]) // deleting all messages await client.messages.deleteAll() ---------------------------------------- TITLE: Publishing QStash Messages in Next.js Route Handler DESCRIPTION: Example of uploading an image and queuing an asynchronous processing task using QStash client. Shows how to publish JSON messages to a QStash queue with error handling and response formatting. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash" import { NextResponse } from "next/server" const client = new Client({ token: process.env.QSTASH_TOKEN! }) export const POST = async (req: Request) => { // Image uploading logic // 👇 Once uploading is done, queue an image processing task const result = await client.publishJSON({ url: "https://your-api-endpoint.com/process-image", body: { imageId: "123" }, }) return NextResponse.json({ message: "Image queued for processing!", qstashMessageId: result.messageId, }) } ---------------------------------------- TITLE: Publishing a GET Request with Callback URLs in Python DESCRIPTION: This example shows how to publish a message with callback URLs for success and failure scenarios. It changes the HTTP method to GET and specifies callback URLs where QStash will return the response of the publish request. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, callback="https://my-callback...", failure_callback="https://my-failure-callback...", method="GET", ) ---------------------------------------- TITLE: Enqueueing a QStash Message with curl DESCRIPTION: This curl command demonstrates how to enqueue a message to a QStash queue called 'myQueue' with a destination URL. It includes authorization via bearer token, content type specification, and several Upstash-specific headers for controlling the HTTP method, retry count, and header forwarding. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/enqueue.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST "https://qstash.upstash.io/v2/enqueue/myQueue/https://www.example.com" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -H "Upstash-Method: POST" \ -H "Upstash-Retries: 3" \ -H "Upstash-Forward-Custom-Header: custom-value" \ -d '{"message":"Hello, World!"}' ---------------------------------------- TITLE: Visualizing URL Group Message Flow with Mermaid DESCRIPTION: A mermaid diagram showing how messages flow from publisher through a URL Group to multiple subscribed endpoints, demonstrating the fan-out pattern and task creation process. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/url-groups.mdx#2025-04-05_snippet_0 LANGUAGE: mermaid CODE: eNp1kl1rgzAUhv9KyOWoddXNtrkYVNdf0F0U5ijRHDVMjctHoRT_-2KtaztUQeS8j28e8JxxKhhggpWmGt45zSWtnKMX13GN7PX59IUc5w19iIanBDUmKbkq-qwfXuKdSVQqeQLssK1ZI3itVQ9dekdzdO6Ja9ntKKq-DxtEoP4xYGCIr-OOGCoOG4IYlPwIcqBu0V0XQRK0PE0w9lyCvP1-iB1n1CgcNwofjcJpo_Cua8ooHDWadIrGnaJHp2jaKbrrmnKK_jl1d9s98AxXICvKmd2fy8-MsS6gghgT-5oJCUrH2NKWNA2zi7BlXAuJSUZLBTNMjRa7U51ioqWBAbpu4R9VCsrAfnTG-tR0u5pzpW1lKuqM593cyNKOC60bRVy3i-c514VJ5qmoXMVZQaUujuvADbxgRT0fgqVPX32fpclivcq8l0XGls8Lj-K2bX8Bx2nzPg ---------------------------------------- TITLE: Publishing with Content-Based Deduplication in Python DESCRIPTION: This snippet demonstrates how to enable content-based deduplication for QStash messages. When enabled, QStash will not deliver duplicate messages with the same content. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_5 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, content_based_deduplication=True, ) ---------------------------------------- TITLE: Publishing HTML Content with QStash in TypeScript DESCRIPTION: This snippet demonstrates how to publish HTML content instead of JSON using the QStash client. It sets the appropriate Content-Type header for HTML. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/publish.mdx#2025-04-05_snippet_4 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publish({ url: "https://my-api...", body: "

Hello World

", headers: { "Content-Type": "text/html", }, }); ---------------------------------------- TITLE: Publishing JSON to a URL with Delay and Headers in Python DESCRIPTION: This example demonstrates how to publish a JSON message to a URL with a 3-second delay and custom headers. The client is initialized with your QStash token, and the response includes a message ID that can be used for tracking. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_0 LANGUAGE: python CODE: from qstash import QStash client = QStash("") res = client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "test-header": "test-value", }, delay="3s", ) print(res.message_id) ---------------------------------------- TITLE: Publishing Message with Absolute Delay using Python Client DESCRIPTION: This Python code uses the qstash library to publish a JSON message with an absolute delay. It shows how to use the not_before parameter in the publish_json method to specify a Unix timestamp for message delivery. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/delay.mdx#2025-04-05_snippet_5 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "test-header": "test-value", }, not_before=1657104947, ) ---------------------------------------- TITLE: Retrieving QStash Signing Keys in Python DESCRIPTION: This snippet shows how to retrieve the current and next signing keys from QStash using the Python client. It initializes a QStash client with a token and uses the signing_key.get() method to fetch the keys. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/keys.mdx#2025-04-05_snippet_0 LANGUAGE: python CODE: from qstash import QStash client = QStash("") signing_key = client.signing_key.get() print(signing_key.current, signing_key.next) ---------------------------------------- TITLE: Implementing Deduplication ID in QStash DESCRIPTION: Examples of how to set a custom deduplication ID when publishing messages to QStash using the 'Upstash-Deduplication-Id' header. This allows for manual control over message deduplication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/deduplication.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Deduplication-Id: abcdef" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api..."' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, deduplicationId: "abcdef", }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, deduplication_id="abcdef", ) ---------------------------------------- TITLE: Publishing Message to Endpoint DESCRIPTION: Basic example of publishing a message to an endpoint using QStash with authentication and JSON payload SOURCE: https://github.com/upstash/docs/blob/main/qstash/overall/apiexamples.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' LANGUAGE: typescript CODE: const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, ) # Async version is also available ---------------------------------------- TITLE: Publishing QStash Message Using Python DESCRIPTION: Example of publishing a message to QStash using Python requests library, showing header configuration and JSON payload formatting. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/publish.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', 'Upstash-Method': 'POST', 'Upstash-Delay': '10s', 'Upstash-Retries': '3', 'Upstash-Forward-Custom-Header': 'custom-value', } json_data = { 'message': 'Hello, World!', } response = requests.post( 'https://qstash.upstash.io/v2/publish/https://www.example.com', headers=headers, json=json_data ) ---------------------------------------- TITLE: Scheduling to a URL Group in Python DESCRIPTION: This snippet demonstrates how to create a schedule for a URL group in QStash using the Python client. It sets up a schedule to publish a message to a specified URL group every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.create( destination="url-group-name", cron="* * * * *", ) ---------------------------------------- TITLE: Overwriting an Existing Schedule in TypeScript DESCRIPTION: This snippet demonstrates how to overwrite an existing schedule or create a new one with a specific ID in QStash using the TypeScript client. It sets up a schedule with a given ID to publish a message to a specified URL every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_8 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", scheduleId: "existingScheduleId", cron: "* * * * *", }); ---------------------------------------- TITLE: Publishing to URL Group DESCRIPTION: Example of publishing a message to multiple endpoints using URL Groups feature in QStash SOURCE: https://github.com/upstash/docs/blob/main/qstash/overall/apiexamples.mdx#2025-04-05_snippet_1 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/myUrlGroup' LANGUAGE: typescript CODE: const client = new Client({ token: "" }); await client.publishJSON({ urlGroup: "myUrlGroup", body: { hello: "world", }, }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url_group="my-url-group", body={ "hello": "world", }, ) # Async version is also available ---------------------------------------- TITLE: Retrieving a QStash Message in TypeScript DESCRIPTION: This snippet demonstrates how to retrieve a specific message from QStash using its ID. It requires the @upstash/qstash client library and a valid QStash token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/messages.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const messages = client.messages const msg = await messages.get("msgId"); ---------------------------------------- TITLE: Creating Hourly Schedule with Callbacks in Python using QStash DESCRIPTION: Demonstrates creating an hourly schedule with success and failure callback URLs. The callbacks will be triggered based on the execution result of the scheduled task. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.create( destination="https://my-api...", cron="0 * * * *", callback="https://my-callback...", failure_callback="https://my-failure-callback...", ) ---------------------------------------- TITLE: Delayed Message Publishing DESCRIPTION: Publishing a message with a 5-minute delay using the Upstash-Delay header SOURCE: https://github.com/upstash/docs/blob/main/qstash/overall/apiexamples.mdx#2025-04-05_snippet_2 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Delay: 5m" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' LANGUAGE: typescript CODE: const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, delay: 300, }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, delay="5m", ) # Async version is also available ---------------------------------------- TITLE: Upserting a QStash Queue with Python DESCRIPTION: This code example demonstrates how to create or update a QStash queue using Python's requests library. It sets up the appropriate headers and JSON payload for the API call. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/upsert.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', } json_data = { "queueName": "my-queue" , "parallelism" : 5, } response = requests.post( 'https://qstash.upstash.io/v2/queues/', headers=headers, json=json_data ) ---------------------------------------- TITLE: Creating Schedule with Timeout in Python using QStash DESCRIPTION: Creates a schedule with a specified timeout duration of 30 seconds. The timeout parameter controls how long QStash waits for the endpoint to respond. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_6 LANGUAGE: python CODE: from qstash import QStash client = QStash("") schedule_id = client.schedule.create( destination="https://my-api...", cron="*/5 * * * *", timeout="30s", ) print(schedule_id) ---------------------------------------- TITLE: Creating URL Groups and Endpoints with Python Client in QStash DESCRIPTION: This Python code uses the qstash library to create URL Groups and add endpoints. It initializes a client with a QStash token and uses the url_group.upsert_endpoints method to create multiple endpoints within a URL Group. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/url-group-endpoint.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.url_group.upsert_endpoints( url_group="url-group-name", endpoints=[ {"name": "endpoint1", "url": "https://example.com"}, {"name": "endpoint2", "url": "https://somewhere-else.com"}, ], ) ---------------------------------------- TITLE: Publishing Message to RequestCatcher with cURL DESCRIPTION: Specific example of publishing a message to QStash using cURL with RequestCatcher as the destination endpoint for testing purposes. SOURCE: https://github.com/upstash/docs/blob/main/qstash/overall/getstarted.mdx#2025-04-05_snippet_1 LANGUAGE: bash CODE: curl -XPOST \ -H 'Authorization: Bearer ' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://firstqstashmessage.requestcatcher.com/test' ---------------------------------------- TITLE: Remove Endpoints using Node.js DESCRIPTION: Makes a DELETE request to remove endpoints from a URL Group using Node.js fetch API. Requires authorization token and accepts a body object with endpoints to remove. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove-endpoint.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch("https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints", { method: "DELETE", headers: { Authorization: "Bearer ", "Content-Type": "application/json", }, body: { endpoints: [ { name: "endpoint1", }, { url: "https://somewhere-else.com", }, ], }, }); ---------------------------------------- TITLE: Publishing LLM Request with Anthropic in TypeScript DESCRIPTION: This snippet demonstrates how to publish a JSON request to Anthropic's API using QStash. It specifies the LLM provider as Anthropic and includes a callback URL for handling responses asynchronously. SOURCE: https://github.com/upstash/docs/blob/main/qstash/integrations/anthropic.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { anthropic, Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.publishJSON({ api: { name: "llm", provider: anthropic({ token: "" }) }, body: { model: "claude-3-5-sonnet-20241022", messages: [{ role: "user", content: "Summarize recent tech trends." }], }, callback: "https://example.com/callback", }); ---------------------------------------- TITLE: Implementing Content-Based Deduplication in QStash DESCRIPTION: Examples of how to enable automatic content-based deduplication in QStash using the 'Upstash-Content-Based-Deduplication' header. This creates a unique deduplication ID based on the destination, body, and specified headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/deduplication.mdx#2025-04-05_snippet_1 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Content-Based-Deduplication: true" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/...' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, contentBasedDeduplication: true, }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, content_based_deduplication=True, ) ---------------------------------------- TITLE: Remove URL Group using Node.js DESCRIPTION: Makes a DELETE request to remove a URL group using Node.js fetch API with bearer token authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/topics/my-url-group', { method: 'DELETE', headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Deleting a URL Group in QStash DESCRIPTION: Deletes an entire URL group from QStash using the urlGroups.delete method. Only requires the name of the URL group to be deleted. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/url-groups.mdx#2025-04-05_snippet_4 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.delete("urlGroupName"); ---------------------------------------- TITLE: Demonstrating Key Rotation Process in QStash DESCRIPTION: This code snippet shows the logical process of key rotation in QStash. When keys are rolled, the current key is replaced with the next key, and a new next key is generated to maintain the dual-key system. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/roll-signing-keys.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: currentKey = nextKey nextKey = generateNewKey() ---------------------------------------- TITLE: Configuring QStash Retries with TypeScript DESCRIPTION: This example demonstrates how to set a custom number of retries using the TypeScript client when publishing a JSON message to QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/retry.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, retries: 2, }); ---------------------------------------- TITLE: Removing a QStash Queue using Python DESCRIPTION: This Python code uses the requests library to delete a queue from QStash. It sets the required authorization header with a bearer token for authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/remove.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.delete( 'https://qstash.upstash.io/v2/queue/my-queue', headers=headers ) ---------------------------------------- TITLE: Publishing to Kafka via QStash using cURL DESCRIPTION: This curl command sends a POST request to the QStash endpoint to publish a message to a Kafka topic. It requires the Kafka URL, topic name, user credentials, and QStash token. The message body is 'hello world'. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/kafka.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl -XPOST 'https://qstash.upstash.io/v2/publish//webhook?topic=&user=&pass=' \ -H 'Authorization: Bearer ' \ -d 'hello world' ---------------------------------------- TITLE: Callback Response Structure DESCRIPTION: JSON structure of the callback response containing status, headers, body, and various metadata about the original request. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/callbacks.mdx#2025-04-05_snippet_1 LANGUAGE: json CODE: { "status": 200, "header": { "key": ["value"] }, "body": "YmFzZTY0IGVuY29kZWQgcm9keQ==", "retried": 2, "maxRetries": 3, "sourceMessageId": "msg_xxx", "topicName": "myTopic", "endpointName": "myEndpoint", "url": "http://myurl.com", "method": "GET", "sourceHeader": { "key": "value" }, "sourceBody": "YmFzZTY0kZWQgcm9keQ==", "notBefore": "1701198458025", "createdAt": "1701198447054", "scheduleId": "scd_xxx", "callerIP": "178.247.74.179" } ---------------------------------------- TITLE: Retrieving a Specific DLQ Message in Python DESCRIPTION: This code snippet shows how to retrieve a specific message from the QStash Dead Letter Queue using its ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/dlq.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") msg = client.dlq.get("") ---------------------------------------- TITLE: Publishing Delayed JSON Message with TypeScript Client DESCRIPTION: This TypeScript code uses the @upstash/qstash client to publish a JSON message with a 60-second delay. It demonstrates how to use the delay parameter in the publishJSON method. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/delay.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, delay: 60, }); ---------------------------------------- TITLE: Publishing to URL Group with Delay and Headers in TypeScript DESCRIPTION: This snippet shows how to publish a JSON message to a URL group using the QStash client, including a 3-second delay and custom headers. It also demonstrates how to handle the response for multiple URLs in the group. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/publish.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ urlGroup: "my-url-group", body: { hello: "world" }, headers: { "test-header": "test-value" }, delay: "3s", }); // When publishing to a URL Group, the response is an array of messages for each URL in the URL Group console.log(res[0].messageId); ---------------------------------------- TITLE: Publishing Messages with Failure Callbacks - Multi-language Examples DESCRIPTION: Examples of publishing messages with failure callback URLs using different programming languages. Shows implementation for handling failed message delivery scenarios. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/callbacks.mdx#2025-04-05_snippet_3 LANGUAGE: bash CODE: curl -X POST \ https://qstash.upstash.io/v2/publish/ \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Failure-Callback: ' \ -d '{ "hello": "world" }' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, failureCallback: "https://my-callback...", }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, failure_callback="https://my-callback...", ) ---------------------------------------- TITLE: Deleting a DLQ Message in Python DESCRIPTION: This snippet demonstrates how to delete a specific message from the QStash Dead Letter Queue using its ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/dlq.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.dlq.delete("") ---------------------------------------- TITLE: Upserting a QStash Queue with cURL DESCRIPTION: This snippet demonstrates how to create or update a QStash queue using a cURL request. It specifies the queue name and parallelism (number of parallel consumers) in the request body. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/upsert.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -XPOST https://qstash.upstash.io/v2/queues/ \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "queueName": "my-queue" , "parallelism" : 5, }' ---------------------------------------- TITLE: Batching Messages to Multiple Destinations with QStash DESCRIPTION: Demonstrates how to send a batch of messages to multiple destinations using cURL, TypeScript, and Python. This method allows sending messages to different endpoints in a single request. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/batch.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XPOST https://qstash.upstash.io/v2/batch \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d ' [ { "destination": "https://example.com/destination1" }, { "destination": "https://example.com/destination2" } ]' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; // Each message is the same as the one you would send with the publish endpoint const client = new Client({ token: "" }); const res = await client.batchJSON([ { url: "https://example.com/destination1", }, { url: "https://example.com/destination2", }, ]); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.batch_json( [ {"url": "https://example.com/destination1"}, {"url": "https://example.com/destination2"}, ] ) ---------------------------------------- TITLE: Retrieving QStash Message using curl DESCRIPTION: Demonstrates how to retrieve a QStash message by its ID using a curl command. Requires an authorization bearer token and the message ID to be included in the URL path. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/get.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/messages/msg_123 \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Enqueueing a QStash Message with Node.js DESCRIPTION: This Node.js code example shows how to use the fetch API to enqueue a message to a QStash queue. It includes setting the required headers for authentication and message configuration, as well as formatting the message body as JSON. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/enqueue.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch( "https://qstash.upstash.io/v2/enqueue/myQueue/https://www.example.com", { method: "POST", headers: { Authorization: "Bearer ", "Content-Type": "application/json", "Upstash-Method": "POST", "Upstash-Retries": "3", "Upstash-Forward-Custom-Header": "custom-value", }, body: JSON.stringify({ message: "Hello, World!", }), } ); ---------------------------------------- TITLE: QStash Backoff Algorithm Formula DESCRIPTION: This code snippet shows the mathematical formula used by QStash's exponential backoff algorithm to calculate retry delays based on the number of retries, with a maximum cap of 1 day. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/retry.mdx#2025-04-05_snippet_3 LANGUAGE: text CODE: n = how many times this request has been retried delay = min(86400, e ** (2.5*n)) // in seconds ---------------------------------------- TITLE: QStash Batch API Response Format DESCRIPTION: This JSON snippet illustrates the expected response format from the QStash batch API. It shows how the API returns message IDs and URLs for each message in the batch, including multiple responses for URL group destinations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/batch.mdx#2025-04-05_snippet_1 LANGUAGE: json CODE: [ [ { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint1.com" }, { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint2.com" } ], { "messageId": "msg_...", }, { "messageId": "msg_..." }, { "messageId": "msg_..." } ] ---------------------------------------- TITLE: Retrieving QStash Message using Python DESCRIPTION: Demonstrates how to retrieve a QStash message by its ID using the requests library in Python. Requires an authorization bearer token in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/get.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/messages/msg_123', headers=headers ) ---------------------------------------- TITLE: Configuring Queue Parallelism DESCRIPTION: Examples showing how to set parallelism for a QStash queue. Demonstrates configuration of concurrent message processing capabilities. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/queues.mdx#2025-04-05_snippet_1 LANGUAGE: bash CODE: curl -XPOST https://qstash.upstash.io/v2/queues/ \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "queueName": "my-queue", "parallelism": 5, }' LANGUAGE: typescript CODE: const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.upsert({ parallelism: 1, }) LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.queue.upsert("my-queue", parallelism=5) ---------------------------------------- TITLE: QStash URL Group Response Format DESCRIPTION: This JSON example shows the response format when enqueueing multiple messages to a QStash queue. It includes arrays of message objects, each containing a messageId and destination URL. It also demonstrates the deduplicated flag that appears when a message is identified as a duplicate. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/enqueue.mdx#2025-04-05_snippet_5 LANGUAGE: json CODE: [ { "messageId": "msd_1234", "url": "https://www.example.com" }, { "messageId": "msd_5678", "url": "https://www.somewhere-else.com", "deduplicated": true } ] ---------------------------------------- TITLE: List QStash Queues using Python DESCRIPTION: API request to list all QStash queues using Python requests library. Requires authorization header with a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/list.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/queues', headers=headers ) ---------------------------------------- TITLE: Authenticating QStash API Requests with Bearer Token DESCRIPTION: This snippet demonstrates how to authenticate a QStash API request using a Bearer Token in the Authorization header. The QSTASH_TOKEN should be obtained from the Upstash console. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/authentication.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl https://qstash.upstash.io/v2/publish/... \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Setting up Failure Callbacks in QStash with TypeScript DESCRIPTION: This snippet shows how to use the QStash TypeScript client to publish a JSON message with a failure callback URL. The client will automatically handle the HTTP request and response formatting. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/handling-failures.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, failureCallback: "https://my-callback...", }); ---------------------------------------- TITLE: Implementing Failure Callbacks in QStash using cURL DESCRIPTION: This snippet demonstrates how to set a failure callback when publishing a message to QStash using cURL. The 'Upstash-Failure-Callback' header specifies the URL that will be called if the message fails to be published. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/handling-failures.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl -X POST \ https://qstash.upstash.io/v2/publish/ \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Failure-Callback: ' \ -d '{ "hello": "world" }' ---------------------------------------- TITLE: Publishing Message with cURL DESCRIPTION: Example of how to publish a message to QStash using cURL with a generic endpoint. The request includes authentication token and JSON payload. SOURCE: https://github.com/upstash/docs/blob/main/qstash/overall/getstarted.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl -XPOST \ -H 'Authorization: Bearer ' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://' ---------------------------------------- TITLE: Queue Retrieval API Response DESCRIPTION: This snippet shows the expected JSON response from the QStash API when retrieving a queue. It includes the creation time, update time, queue name, parallelism, and lag of the queue. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/get.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "createdAt": 1623345678001, "updatedAt": 1623345678001, "name": "my-queue", "parallelism" : 5, "lag" : 100 } ---------------------------------------- TITLE: Setting Authorization Header for QStash API Requests DESCRIPTION: Demonstrates how to set the Authorization header for requests to the QStash API using a bearer token. The token is obtained from the Upstash Console. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/security.mdx#2025-04-05_snippet_0 LANGUAGE: plaintext CODE: "Authorization": "Bearer " ---------------------------------------- TITLE: Pausing QStash Queue using Go DESCRIPTION: This Go code uses the qstash-go library to pause a QStash queue. It initializes a client with the QStash token and calls the Pause method on the Queues object with the queue name. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/pause.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: package main import ( "github.com/upstash/qstash-go" ) func main() { client := qstash.NewClient("") // error checking is omitted for brevity err := client.Queues().Pause("") } ---------------------------------------- TITLE: Handling Daily Rate Limit Error in QStash with TypeScript DESCRIPTION: This snippet demonstrates how to catch and handle a daily rate limit error when making a publish request with QStash. It uses the QstashDailyRatelimitError class to identify when the daily request limit has been exceeded and provides access to the reset time. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/api-ratelimiting.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { QstashDailyRatelimitError } from "@upstash/qstash"; try { // Example of a publish request that could hit the daily rate limit const result = await client.publishJSON({ url: "https://my-api...", // or urlGroup: "the name or id of a url group" body: { hello: "world", }, }); } catch (error) { if (error instanceof QstashDailyRatelimitError) { console.log("Daily rate limit exceeded. Retry after:", error.reset); // Implement retry logic or notify the user } else { console.error("An unexpected error occurred:", error); } } ---------------------------------------- TITLE: QStash API Response Examples DESCRIPTION: Example JSON responses from the QStash API showing both single URL and URL group responses with message IDs and deduplication status. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/publish.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "messageId": "msd_1234", "url": "https://www.example.com" } LANGUAGE: json CODE: [ { "messageId": "msd_1234", "url": "https://www.example.com" }, { "messageId": "msd_5678", "url": "https://www.somewhere-else.com", "deduplicated": true } ] ---------------------------------------- TITLE: Verifying QStash Signatures using Python SDK DESCRIPTION: Implementation of signature verification using the QStash Python SDK's Receiver class to validate request authenticity. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/signature.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import Receiver receiver = Receiver( current_signing_key="YOUR_CURRENT_SIGNING_KEY", next_signing_key="YOUR_NEXT_SIGNING_KEY", ) # ... in your request handler signature, body = req.headers["Upstash-Signature"], req.body receiver.verify( body=body, signature=signature, url="YOUR-SITE-URL", ) ---------------------------------------- TITLE: Handling Chat-based Rate Limit Error in QStash with TypeScript DESCRIPTION: This snippet demonstrates how to handle chat-specific rate limit errors when working with LLM integrations in QStash. It uses the QstashChatRatelimitError class to catch token or request limit errors when making calls to AI providers like OpenAI through QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/api-ratelimiting.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: import { QstashChatRatelimitError, Client, openai } from "@upstash/qstash"; try { // Example of a chat-related request that could hit the chat rate limit const client = new Client({ token: "", }); const result = await client.publishJSON({ api: { name: "llm", provider: openai({ token: process.env.OPENAI_API_KEY! }), }, body: { model: "gpt-3.5-turbo", messages: [ { role: "user", content: "Where is the capital of Turkey?", }, ], }, callback: "https://oz.requestcatcher.com/", }); } catch (error) { if (error instanceof QstashChatRatelimitError) { console.log("Chat rate limit exceeded. Retry after:", error.resetRequests); // Handle chat-specific rate limiting, perhaps by queueing requests } else { console.error("An unexpected error occurred:", error); } } ---------------------------------------- TITLE: Example Response for URL Groups List DESCRIPTION: Shows the JSON response format when successfully listing URL Groups. The response is an array of URL Group objects, each containing creation time, update time, name, and an array of endpoints with their names and URLs. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/list.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: [ { "createdAt": 1623345678001, "updatedAt": 1623345678001, "name": "my-url-group", "endpoints": [ { "name": "my-endpoint", "url": "https://my-endpoint.com" } ] }, // ... ] ---------------------------------------- TITLE: Verifying QStash Signatures using Golang SDK DESCRIPTION: Example showing how to use the QStash Go SDK to verify request signatures, including body reading and error handling. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/signature.mdx#2025-04-05_snippet_2 LANGUAGE: go CODE: import "github.com/qstash/qstash-go" receiver := qstash.NewReceiver("", "NEXT_SIGNING_KEY") // ... in your request handler signature := req.Header.Get("Upstash-Signature") body, err := io.ReadAll(req.Body) // handle err err := receiver.Verify(qstash.VerifyOptions{ Signature: signature, Body: string(body), Url: "YOUR-SITE-URL", // optional }) // handle err ---------------------------------------- TITLE: Using QStash Python SDK for Scheduling DESCRIPTION: Python code example for creating a scheduled task using the QStash Python SDK. This demonstrates how to automate the creation of QStash jobs programmatically. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/python-vercel.mdx#2025-04-05_snippet_7 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.create( destination="https://YOUR_URL.vercel.app/api", cron="0 12 * * *", ) ---------------------------------------- TITLE: Bulk Cancel Messages API Request using Python DESCRIPTION: Example of how to make a DELETE request to the Bulk Cancel Messages API using Python requests library. It shows how to set headers and pass message IDs in the request body. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/bulk-cancel.mdx#2025-04-05_snippet_3 LANGUAGE: Python CODE: import requests headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', } data = { "messageIds": [ "msg_id_1", "msg_id_2", "msg_id_3" ] } response = requests.delete( 'https://qstash.upstash.io/v2/messages', headers=headers, data=data ) ---------------------------------------- TITLE: JSON Response Structure for DLQ Messages in QStash DESCRIPTION: This snippet shows the JSON structure of a successful response when querying DLQ messages. It includes an array of messages, each containing details such as messageId, topicId, URL, method, headers, body, creation timestamp, and state. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/listMessages.mdx#2025-04-05_snippet_1 LANGUAGE: json CODE: { "messages": [ { "messageId": "msg_123", "topicId": "tpc_123", "url":"https://example.com", "method": "POST", "header": { "My-Header": ["my-value"] }, "body": "{\"foo\":\"bar\"}", "createdAt": 1620000000000, "state": "failed" } ] } ---------------------------------------- TITLE: Verifying QStash Message Signatures with TypeScript DESCRIPTION: This code demonstrates how to verify the signature of a message received from QStash using the Receiver class from the @upstash/qstash SDK. It initializes a Receiver instance with signing keys and uses it to validate the signature against the message body and URL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/receiver.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Receiver } from "@upstash/qstash"; const receiver = new Receiver({ currentSigningKey: "YOUR_CURRENT_SIGNING_KEY", nextSigningKey: "YOUR_NEXT_SIGNING_KEY", }); // ... in your request handler const signature = req.headers["Upstash-Signature"]; const body = req.body; const isValid = receiver.verify({ body, signature, url: "YOUR-SITE-URL", }); ---------------------------------------- TITLE: Retrieving a Queue with Node.js DESCRIPTION: This snippet shows how to retrieve a queue using Node.js. It uses the fetch API to send a GET request to the QStash API endpoint, including the queue name in the URL and an authorization token in the header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/get.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/queue/my-queue', { headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: QStash Events API Response Example DESCRIPTION: This snippet provides an example of a successful response from the QStash events API. It includes a cursor for pagination and an array of event objects with details such as timestamp, message ID, state, URL, headers, and body. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/events/list.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "cursor": "1686652644442-12", "events":[ { "time": "1686652644442", "messageId": "msg_123", "state": "delivered", "url": "https://example.com", "header": { "Content-Type": [ "application/x-www-form-urlencoded" ] }, "body": "bWVyaGFiYSBiZW5pbSBhZGltIHNhbmNhcg==" } ] } ---------------------------------------- TITLE: Receiving QStash Messages in Next.js Route Handler DESCRIPTION: Implementation of a message receiver endpoint that processes queued tasks. Demonstrates signature verification using QStash's security middleware and handling of incoming message payloads. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" // 👇 Verify that this messages comes from QStash export const POST = verifySignatureAppRouter(async (req: Request) => { const body = await req.json() const { imageId } = body as { imageId: string } // Image processing logic, i.e. using sharp return new Response(`Image with id "${imageId}" processed successfully.`) }) ---------------------------------------- TITLE: Retrieving a Queue with cURL DESCRIPTION: This snippet demonstrates how to retrieve a queue using cURL. It sends a GET request to the QStash API endpoint with the queue name in the URL path and includes an authorization token in the header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/get.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Deleting QStash Queue DESCRIPTION: Demonstrates how to delete an existing queue using the QStash client. The example removes a queue named 'upstash-queue'. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/queues.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.delete(queue_name) ---------------------------------------- TITLE: QStash Queues Response Format DESCRIPTION: Example JSON response from the QStash queues API. Returns an array of queue objects containing creation time, update time, name, parallelism, and lag information. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/list.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: [ { "createdAt": 1623345678001, "updatedAt": 1623345678001, "name": "my-queue", "parallelism" : 5, "lag" : 100 }, // ... ] ---------------------------------------- TITLE: Creating Next.js Client Component for Initiating Background Jobs DESCRIPTION: This code snippet defines a React component that allows users to start a background job using QStash. It includes state management for loading and message display, and uses a server action to initiate the job. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_8 LANGUAGE: tsx CODE: "use client" import { startBackgroundJob } from "@/app/actions"; import { useState } from "react"; export default function Home() { const [loading, setLoading] = useState(false); const [msg, setMsg] = useState(""); async function handleClick() { setLoading(true); const messageId = await startBackgroundJob(); if (messageId) { setMsg(`Started job with ID ${messageId}`); } else { setMsg("Failed to start background job"); } setLoading(false); } return (
{loading &&
Loading...
} {msg &&

{msg}

}
); } ---------------------------------------- TITLE: Retrieving a Queue with Go DESCRIPTION: This snippet shows how to retrieve a queue using Go. It creates a new HTTP GET request to the QStash API endpoint, sets the authorization header, and sends the request using the default HTTP client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/get.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/queue/my-queue", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Example JSON Response for Get Schedule DESCRIPTION: This JSON snippet represents an example successful response from the Get Schedule API. It includes details such as the schedule ID, creation time, cron expression, destination URL, HTTP method, headers, body, and retry count. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/get.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "scheduleId": "scd_1234", "createdAt": 1623345678001, "cron": "0 0 1 * *", "destination": "https://example.com", "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"message\":\"hello\"}", "retries": 3 } ---------------------------------------- TITLE: Implementing Server Action for QStash Job Initiation in Next.js DESCRIPTION: This server-side action initializes a QStash client and publishes a JSON message to start a background job. It handles errors and returns the message ID on success. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_9 LANGUAGE: typescript CODE: "use server" import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }); export async function startBackgroundJob() { try { const response = await qstashClient.publishJSON({ "url": "https://qstash-bg-job.vercel.app/api/long-task", body: { "hello": "world" } }); return response.messageId; } catch (error) { console.error(error); return null; } } ---------------------------------------- TITLE: Configuring QStash Retries with Python DESCRIPTION: This example shows how to set a custom number of retries using the Python client when publishing a JSON message to QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/retry.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, retries=2, ) ---------------------------------------- TITLE: Creating QStash Queue with Parallelism DESCRIPTION: Shows how to create a new queue with specified parallelism using the QStash client. The example creates a queue named 'upstash-queue' with parallelism set to 2 and prints the queue details. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/queues.mdx#2025-04-05_snippet_0 LANGUAGE: python CODE: from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.upsert(queue_name, parallelism=2) print(client.queue.get(queue_name)) ---------------------------------------- TITLE: QStash URL Response Format DESCRIPTION: This JSON example shows the response format when enqueueing a single message to a QStash queue. It includes the generated messageId and the URL the message will be sent to. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/enqueue.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "messageId": "msd_1234", "url": "https://www.example.com" } ---------------------------------------- TITLE: Creating API Route for Long-Running Task with QStash Verification in Next.js DESCRIPTION: This API route handles a long-running task, making multiple API calls with delays. It uses QStash's signature verification for security. The handler processes the incoming request and returns a success response. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_10 LANGUAGE: typescript CODE: import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" async function handler(request: Request) { const data = await request.json() for (let i = 0; i < 10; i++) { await fetch("https://firstqstashmessage.requestcatcher.com/test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, }) await new Promise((resolve) => setTimeout(resolve, 500)) } return Response.json({ success: true }) } export const POST = verifySignatureAppRouter(handler) ---------------------------------------- TITLE: Publishing Messages with Callbacks - Multi-language Examples DESCRIPTION: Examples of publishing messages to QStash with callback URLs using different programming languages. Shows how to set callback URLs using the Upstash-Callback header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/callbacks.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl -X POST \ https://qstash.upstash.io/v2/publish/https://my-api... \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Callback: ' \ -d '{ "hello": "world" }' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, callback: "https://my-callback...", }); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, callback="https://my-callback...", ) ---------------------------------------- TITLE: Retrieving a message from QStash DLQ using curl DESCRIPTION: This curl command demonstrates how to make a GET request to retrieve a specific message from the QStash Dead Letter Queue (DLQ) using its DLQ ID. It requires authorization via a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/getMessage.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X GET https://qstash.upstash.io/v2/dlq/my-dlq-id \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Publishing a Message to QStash Webhook Endpoint DESCRIPTION: This bash command demonstrates how to publish a message to the QStash webhook endpoint using curl. It sends a POST request with JSON payload and includes the necessary authorization header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/deno-deploy.mdx#2025-04-05_snippet_1 LANGUAGE: bash CODE: curl --request POST "https://qstash.upstash.io/v2/publish/https://early-frog-33.deno.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ---------------------------------------- TITLE: Retrieving a URL Group by Name with QStash in Python DESCRIPTION: This code snippet shows how to retrieve a specific URL group by its name using the QStash client. It prints the group name and its associated endpoints. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/url-groups.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") url_group = client.url_group.get("my-url-group") print(url_group.name, url_group.endpoints) ---------------------------------------- TITLE: Standard JSON Response for QStash LLM API Chat Completions DESCRIPTION: This snippet shows the standard JSON response format returned by QStash's LLM API for chat completions. It includes the completion ID, metadata, message content, and token usage statistics. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/llm/create.mdx#2025-04-05_snippet_3 LANGUAGE: json CODE: { "id": "cmpl-abefcf66fae945b384e334e36c7fdc97", "object": "chat.completion", "created": 1717483987, "model": "meta-llama/Meta-Llama-3-8B-Instruct", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The capital of Turkey is Ankara." }, "logprobs": null, "finish_reason": "stop", "stop_reason": null } ], "usage": { "prompt_tokens": 18, "total_tokens": 26, "completion_tokens": 8 } } ---------------------------------------- TITLE: Deleting a Message from DLQ using cURL in Shell DESCRIPTION: This snippet demonstrates how to use cURL to send a DELETE request to remove a specific message from the Dead Letter Queue in QStash. It requires the DLQ ID and an authorization token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/deleteMessage.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X DELETE https://qstash.upstash.io/v2/dlq/my-dlq-id \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Initializing AWS Lambda Project with CDK DESCRIPTION: Commands to create a new AWS Lambda project using CDK and install required dependencies. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/nodejs.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: mkdir my-app cd my-app cdk init app -l typescript npm i esbuild @upstash/qstash mkdir lambda touch lambda/index.ts ---------------------------------------- TITLE: Retrieving a URL Group by Name in QStash DESCRIPTION: Fetches a URL group from QStash by its name using the urlGroups.get method. The returned object contains the group name and its associated endpoints which are logged to the console. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/url-groups.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; const urlGroup = await urlGroups.get("urlGroupName"); console.log(urlGroup.name, urlGroup.endpoints); ---------------------------------------- TITLE: Response Format for DLQ Message Deletion DESCRIPTION: JSON response structure showing the number of deleted messages from the DLQ. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/deleteMessages.mdx#2025-04-05_snippet_0 LANGUAGE: json CODE: { "deleted": number } ---------------------------------------- TITLE: QStash Verification Function Implementation DESCRIPTION: Detailed implementation of the verify function used for manual webhook verification. Handles JWT validation, signature verification, and payload claims checking. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/nodejs.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: async function verify( jwt: string, signingKey: string, body: string | null, url: string ): Promise { const split = jwt.split(".") if (split.length != 3) { throw new Error("Invalid JWT") } const [header, payload, signature] = split if ( signature != createHmac("sha256", signingKey) .update(`${header}.${payload}`) .digest("base64url") ) { throw new Error("Invalid JWT signature") } const p: { sub: string iss: string exp: number nbf: number body: string } = JSON.parse(Buffer.from(payload, "base64url").toString()) if (p.iss !== "Upstash") { throw new Error(`invalid issuer: ${p.iss}, expected "Upstash"`) } if (p.sub !== url) { throw new Error(`invalid subject: ${p.sub}, expected "${url}"`) } const now = Math.floor(Date.now() / 1000) if (now > p.exp) { throw new Error("token has expired") } if (now < p.nbf) { throw new Error("token is not yet valid") } if (body != null) { if ( p.body.replace(/=+$/, "") != createHash("sha256").update(body).digest("base64url") ) { throw new Error("body hash does not match") } } } ---------------------------------------- TITLE: Implementing QStash Webhook Receiver in Deno Deploy DESCRIPTION: This TypeScript code sets up a Deno server that receives webhooks from QStash, verifies their signatures, and processes them. It uses the Deno standard HTTP server and the Upstash QStash Receiver library. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/deno-deploy.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { serve } from "https://deno.land/std@0.142.0/http/server.ts"; import { Receiver } from "https://deno.land/x/upstash_qstash@v0.1.4/mod.ts"; serve(async (req: Request) => { const r = new Receiver({ currentSigningKey: Deno.env.get("QSTASH_CURRENT_SIGNING_KEY")!, nextSigningKey: Deno.env.get("QSTASH_NEXT_SIGNING_KEY")!, }); const isValid = await r .verify({ signature: req.headers.get("Upstash-Signature")!, body: await req.text(), }) .catch((err: Error) => { console.error(err); return false; }); if (!isValid) { return new Response("Invalid signature", { status: 401 }); } console.log("The signature was valid"); // do work return new Response("OK", { status: 200 }); }); ---------------------------------------- TITLE: Remove Endpoints using Go DESCRIPTION: Makes a DELETE request to remove endpoints from a URL Group using Go's http package. Requires authorization token and sends JSON data with endpoints to remove. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove-endpoint.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: var data = strings.NewReader(`{ "endpoints": [ { "name": "endpoint1", }, { "url": "https://somewhere-else.com" } ] }`) req, err := http.NewRequest("DELETE", "https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints", data) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Cancelling QStash Message with cURL DESCRIPTION: This example demonstrates how to cancel a QStash message using a cURL command. It performs a DELETE request to the QStash API with the message ID and requires an authorization token for authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/cancel.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XDELETE https://qstash.upstash.io/v2/messages/msg_123 \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Implementing AWS Lambda Handler for QStash Webhook Verification DESCRIPTION: Python function to handle incoming Lambda events, extract necessary information, and verify the QStash signature using both current and next signing keys. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/python.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: def lambda_handler(event, context): # parse the inputs current_signing_key = os.environ['QSTASH_CURRENT_SIGNING_KEY'] next_signing_key = os.environ['QSTASH_NEXT_SIGNING_KEY'] headers = event['headers'] signature = headers['upstash-signature'] url = "https://{}{}".format(event["requestContext"]["domainName"], event["rawPath"]) body = None if 'body' in event: body = event['body'] # check verification now try: verify(signature, current_signing_key, body, url) except Exception as e: print("Failed to verify signature with current signing key:", e) try: verify(signature, next_signing_key, body, url) except Exception as e2: return { "statusCode": 400, "body": json.dumps({ "error": str(e2), }), } # Your logic here... return { "statusCode": 200, "body": json.dumps({ "message": "ok", }), } ---------------------------------------- TITLE: Deleting a Schedule in QStash using TypeScript DESCRIPTION: Removes a schedule from QStash using its ID. This permanently deletes the schedule configuration. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_6 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.delete("scheduleId"); ---------------------------------------- TITLE: Cancelling QStash Message with Node.js DESCRIPTION: This Node.js example shows how to cancel a QStash message by making a DELETE request using the fetch API. It requires the message ID in the URL path and an authorization token in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/cancel.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/messages/msg_123', { method: 'DELETE', headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Implementing QStash Signature Verification Function in Python DESCRIPTION: Python function to verify the JWT token signature, decode claims, and validate the request body hash for QStash webhooks. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/python.mdx#2025-04-05_snippet_3 LANGUAGE: python CODE: def verify(jwt_token, signing_key, body, url): split = jwt_token.split(".") if len(split) != 3: raise Exception("Invalid JWT.") header, payload, signature = split message = header + '.' + payload generated_signature = base64.urlsafe_b64encode(hmac.new(bytes(signing_key, 'utf-8'), bytes(message, 'utf-8'), digestmod=hashlib.sha256).digest()).decode() if generated_signature != signature and signature + "=" != generated_signature : raise Exception("Invalid JWT signature.") decoded = jwt.decode(jwt_token, options={"verify_signature": False}) sub = decoded['sub'] iss = decoded['iss'] exp = decoded['exp'] nbf = decoded['nbf'] decoded_body = decoded['body'] if iss != "Upstash": raise Exception("Invalid issuer: {}".format(iss)) if sub.rstrip("/") != url.rstrip("/"): raise Exception("Invalid subject: {}".format(sub)) now = time.time() if now > exp: raise Exception("Token has expired.") if now < nbf: raise Exception("Token is not yet valid.") if body != None: while decoded_body[-1] == "=": decoded_body = decoded_body[:-1] m = hashlib.sha256() m.update(bytes(body, 'utf-8')) m = m.digest() generated_hash = base64.urlsafe_b64encode(m).decode() if generated_hash != decoded_body and generated_hash != decoded_body + "=" : raise Exception("Body hash doesn't match.") ---------------------------------------- TITLE: Implementing RatePerSecond Flow Control in QStash DESCRIPTION: Demonstrates how to set a rate limit of 10 calls per second to an endpoint using QStash's flow control feature. Shows implementation in both TypeScript client and cURL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/flowcontrol.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", ratePerSecond: 10 }, }); LANGUAGE: bash CODE: curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:Rate=10" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ---------------------------------------- TITLE: Publishing Delayed JSON Message with Python Client DESCRIPTION: This Python code uses the qstash library to publish a JSON message with a 60-second delay. It shows how to use the delay parameter in the publish_json method of the QStash client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/delay.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "test-header": "test-value", }, delay="60s", ) ---------------------------------------- TITLE: Canceling Single QStash Message - Python DESCRIPTION: Shows how to cancel/delete a specific message from QStash using its message ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/messages.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.cancel("") ---------------------------------------- TITLE: Creating Makefile for AWS Lambda Python Function Deployment DESCRIPTION: Makefile script to install dependencies, copy the Lambda function, and create a deployment package for AWS Lambda. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/python.mdx#2025-04-05_snippet_4 LANGUAGE: yaml CODE: zip: rm -rf dist pip3 install --target ./dist pyjwt cp lambda_function.py ./dist/lambda_function.py cd dist && zip -r lambda.zip . mv ./dist/lambda.zip ./ ---------------------------------------- TITLE: Creating Scheduled Message with Node.js DESCRIPTION: This snippet shows how to create a scheduled message using Node.js. It uses the fetch API to send a POST request to the QStash API with the required headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/create.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/schedules/https://www.example.com/endpoint', { method: 'POST', headers: { 'Authorization': 'Bearer ', 'Upstash-Cron': '*/5 * * * *' } }); ---------------------------------------- TITLE: Sending GET Request to List Schedules in QStash API (cURL) DESCRIPTION: This snippet demonstrates how to send a GET request to the QStash API endpoint to list all schedules using cURL. It requires an authorization token to be set in the header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/list.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/schedules \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Navigating to Project Directory DESCRIPTION: Command to change to the created project directory. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/python-vercel.mdx#2025-04-05_snippet_1 LANGUAGE: bash CODE: cd clean-db-cron ---------------------------------------- TITLE: Pausing and Resuming QStash Queue DESCRIPTION: Shows how to pause and resume a queue, and check its paused status. Creates a queue with parallelism 1, pauses it, checks the pause status, and then resumes it. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/queues.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.upsert(queue_name, parallelism=1) client.queue.pause(queue_name) queue = client.queue.get(queue_name) print(queue.paused) # prints True client.queue.resume(queue_name) ---------------------------------------- TITLE: Handling Burst Rate Limit Error in QStash with TypeScript DESCRIPTION: This snippet shows how to handle burst rate limit errors that occur when making too many requests within a short time period (1 second). It uses the QstashRatelimitError class to detect when the burst limit has been exceeded and provides access to the reset timestamp. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/api-ratelimiting.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { QstashRatelimitError } from "@upstash/qstash"; try { // Example of a request that could hit the burst rate limit const result = await client.publishJSON({ url: "https://my-api...", // or urlGroup: "the name or id of a url group" body: { hello: "world", }, }); } catch (error) { if (error instanceof QstashRatelimitError) { console.log("Burst rate limit exceeded. Retry after:", error.reset); // Implement exponential backoff or delay before retrying } else { console.error("An unexpected error occurred:", error); } } ---------------------------------------- TITLE: Getting a Schedule with Python DESCRIPTION: This Python code demonstrates how to retrieve a schedule using the requests library. It sends a GET request to the QStash API with the required authorization header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/get.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/schedules/scd_1234', headers=headers ) ---------------------------------------- TITLE: Installing Redis Client for Python DESCRIPTION: Command to install the Upstash Redis client package for Python. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/python-vercel.mdx#2025-04-05_snippet_2 LANGUAGE: bash CODE: pip install upstash-redis ---------------------------------------- TITLE: Listing All Schedules in QStash using TypeScript DESCRIPTION: Retrieves and logs all schedules configured in the QStash account. This is useful for auditing or managing multiple schedules. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_4 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); console.log(allSchedules); ---------------------------------------- TITLE: Fetching Schedules List from QStash API (JavaScript/Node.js) DESCRIPTION: This code snippet shows how to use the Fetch API in JavaScript/Node.js to send a GET request to the QStash API for listing schedules. It includes setting the authorization header with a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/list.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/schedules', { headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Implementing Database Cleanup Script DESCRIPTION: Python script that connects to Upstash Redis and deletes all keys in the database. This standalone script will be used as the base for our cleanup functionality. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/python-vercel.mdx#2025-04-05_snippet_3 LANGUAGE: python CODE: from upstash_redis import Redis redis = Redis(url="https://YOUR_REDIS_URL", token="YOUR_TOKEN") def delete_all_entries(): keys = redis.keys("*") # Match all keys redis.delete(*keys) delete_all_entries() ---------------------------------------- TITLE: Publishing to a URL Group using TypeScript DESCRIPTION: This snippet demonstrates how to publish a JSON message to a URL group in QStash using the TypeScript client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/publishing.mdx#2025-04-05_snippet_4 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ urlGroup: "my-url-group", body: { "hello": "world" }, }); ---------------------------------------- TITLE: Filtering Logs by State and Count in TypeScript using QStash Client DESCRIPTION: This snippet shows how to filter logs by state and limit the number of results. It uses the 'DELIVERED' state as an example and limits the results to 50 entries. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/logs.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.logs({ filter: { state: "DELIVERED", count: 50 } }); ---------------------------------------- TITLE: Retrieving Schedules from QStash API (Python) DESCRIPTION: This Python code snippet demonstrates how to use the requests library to send a GET request to the QStash API for retrieving the list of schedules. It sets the authorization header with a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/list.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/schedules', headers=headers ) ---------------------------------------- TITLE: Creating HTTP Endpoint for QStash Integration DESCRIPTION: Python script that creates an HTTP endpoint handler using Python's built-in http.server module. This allows QStash to trigger the database cleanup via HTTP POST requests. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/python-vercel.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: from http.server import BaseHTTPRequestHandler from upstash_redis import Redis redis = Redis(url="https://YOUR_REDIS_URL", token="YOUR_TOKEN") def delete_all_entries(): keys = redis.keys("*") # Match all keys redis.delete(*keys) class handler(BaseHTTPRequestHandler): def do_POST(self): delete_all_entries() self.send_response(200) self.end_headers() ---------------------------------------- TITLE: Publishing HTML Content with QStash in Python DESCRIPTION: This example shows how to publish HTML content instead of JSON. The content type is explicitly set to 'text/html' and the message body contains HTML markup. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish( url="https://my-api...", body="

Hello World

", content_type="text/html", ) ---------------------------------------- TITLE: Querying Schedules List from QStash API (Go) DESCRIPTION: This Go code snippet illustrates how to create and send a GET request to the QStash API endpoint for listing schedules. It includes error handling and sets the authorization header with a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/list.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/schedules", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Running localtunnel to expose a local server on port 3000 DESCRIPTION: A simple command to create a public endpoint for a local development server using localtunnel. This exposes your locally running application on port 3000 to the internet with a public URL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/local-tunnel.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: npx localtunnel --port 3000 ---------------------------------------- TITLE: Modifying URL Group Default Headers with cURL in Bash DESCRIPTION: This cURL request patches a URL Group to set default headers that will apply to all requests sent to endpoints within that group. It configures header forwarding and retry settings. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/webhook.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: curl -X PATCH https://qstash.upstash.io/v2/topics/ \ -H "Authorizarion: Bearer " -d '{ "headers": { "Upstash-Header-Forward": ["true"], "Upstash-Retries": "3" } }' ---------------------------------------- TITLE: Installing Next.js and QStash Dependencies DESCRIPTION: Commands to create a new Next.js application and install the QStash package. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_3 LANGUAGE: bash CODE: npx create-next-app@latest qstash-bg-job cd qstash-bg-job npm install @upstash/qstash npm run dev ---------------------------------------- TITLE: Retrieving QStash Signing Keys with cURL DESCRIPTION: Uses cURL to make a GET request to the QStash API endpoint to retrieve signing keys. Requires an authorization token to be included in the request header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/signingKeys/get.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/keys \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Adding ngrok authentication token DESCRIPTION: Command to configure the ngrok CLI with your authentication token after signing up. This is required to use ngrok for creating tunnels to your local environment. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/local-tunnel.mdx#2025-04-05_snippet_1 LANGUAGE: bash CODE: ngrok config add-authtoken XXX ---------------------------------------- TITLE: Wrangler Configuration DESCRIPTION: YAML configuration for setting up QStash credentials in the wrangler.toml file. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_4 LANGUAGE: yaml CODE: [vars] QSTASH_URL="REPLACE_HERE" QSTASH_TOKEN="REPLACE_HERE" QSTASH_CURRENT_SIGNING_KEY="REPLACE_HERE" QSTASH_NEXT_SIGNING_KEY="REPLACE_HERE" ---------------------------------------- TITLE: Retrieving QStash Signing Keys with Node.js DESCRIPTION: Uses the fetch API in Node.js to make a GET request to retrieve QStash signing keys. The authorization token is included in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/signingKeys/get.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/keys', { headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: QStash Test User Credentials DESCRIPTION: Environment variables and credentials for four test users including tokens and signing keys SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/local-development.mdx#2025-04-05_snippet_4 LANGUAGE: javascript CODE: QSTASH_URL=http://localhost:8080 QSTASH_TOKEN=eyJVc2VySUQiOiJkZWZhdWx0VXNlciIsIlBhc3N3b3JkIjoiZGVmYXVsdFBhc3N3b3JkIn0= QSTASH_CURRENT_SIGNING_KEY=sig_7kYjw48mhY7kAjqNGcy6cr29RJ6r QSTASH_NEXT_SIGNING_KEY=sig_5ZB6DVzB1wjE8S6rZ7eenA8Pdnhs LANGUAGE: javascript CODE: QSTASH_URL=http://localhost:8080 QSTASH_TOKEN=eyJVc2VySUQiOiJ0ZXN0VXNlcjEiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9 QSTASH_CURRENT_SIGNING_KEY=sig_7GVPjvuwsfqF65iC8fSrs1dfYruM QSTASH_NEXT_SIGNING_KEY=sig_5NoELc3EFnZn4DVS5bDs2Nk4b7Ua LANGUAGE: javascript CODE: QSTASH_URL=http://localhost:8080 QSTASH_TOKEN=eyJVc2VySUQiOiJ0ZXN0VXNlcjIiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9 QSTASH_CURRENT_SIGNING_KEY=sig_6jWGaWRxHsw4vMSPJprXadyvrybF QSTASH_NEXT_SIGNING_KEY=sig_7qHbvhmahe5GwfePDiS5Lg3pi6Qx LANGUAGE: javascript CODE: QSTASH_URL=http://localhost:8080 QSTASH_TOKEN=eyJVc2VySUQiOiJ0ZXN0VXNlcjMiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9 QSTASH_CURRENT_SIGNING_KEY=sig_5T8FcSsynBjn9mMLBsXhpacRovJf QSTASH_NEXT_SIGNING_KEY=sig_7GFR4YaDshFcqsxWRZpRB161jguD ---------------------------------------- TITLE: Running QStash Binary DESCRIPTION: Command to run QStash development server from downloaded binary SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/local-development.mdx#2025-04-05_snippet_2 LANGUAGE: bash CODE: $ ./qstash dev ---------------------------------------- TITLE: QStash Message Publishing DESCRIPTION: cURL command example for publishing a message to QStash endpoint. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_5 LANGUAGE: bash CODE: curl --request POST "https://qstash.upstash.io/v2/publish/https://cloudflare-workers.upstash.workers.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ---------------------------------------- TITLE: Retrieving QStash Signing Keys with Go DESCRIPTION: Uses the http package in Go to make a GET request to retrieve QStash signing keys. The code handles creating the request, setting the authorization header, and making the request with error handling. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/signingKeys/get.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/keys", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Installing QStash Python Client via pip DESCRIPTION: Installation command for the QStash Python package using pip package manager. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/gettingstarted.mdx#2025-04-05_snippet_0 LANGUAGE: bash CODE: pip install qstash ---------------------------------------- TITLE: Installing QStash Library DESCRIPTION: Command to install the Upstash QStash library as a project dependency. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_2 LANGUAGE: bash CODE: npm install @upstash/qstash ---------------------------------------- TITLE: Querying QStash Logs API using cURL DESCRIPTION: This snippet demonstrates how to make a GET request to the QStash logs API using cURL. It includes the necessary authorization header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/logs/list.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl https://qstash.upstash.io/v2/logs \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Initializing Synchronous QStash Client DESCRIPTION: Setup and initialization of a synchronous QStash client instance using a QStash token for authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/gettingstarted.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json(...) ---------------------------------------- TITLE: Installing Cloudflare CLI DESCRIPTION: Commands to install and initialize a new Cloudflare Workers project using the create-cloudflare CLI tool. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: npm create cloudflare@latest LANGUAGE: shell CODE: yarn create cloudflare@latest ---------------------------------------- TITLE: Sending a Single Email with Resend via QStash DESCRIPTION: This snippet demonstrates how to send a single email using the QStash client with Resend as the provider. It requires both QStash and Resend authentication tokens and supports all parameters from the Resend Send Email API. SOURCE: https://github.com/upstash/docs/blob/main/qstash/integrations/resend.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client, resend } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.publishJSON({ api: { name: "email", provider: resend({ token: "" }), }, body: { from: "Acme ", to: ["delivered@resend.dev"], subject: "Hello World", html: "

It works!

", }, }); ---------------------------------------- TITLE: Retrieving QStash Logs with Python DESCRIPTION: This Python code demonstrates how to make a GET request to the QStash logs API using the requests library. It sets up the necessary headers for authorization. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/logs/list.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/logs', headers=headers ) ---------------------------------------- TITLE: Creating a Client Component with Background Job Trigger in Next.js DESCRIPTION: A Next.js client component that contains a button to initiate a background job. When clicked, it sends a POST request to a server endpoint that will process the job asynchronously using QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/background-jobs.mdx#2025-04-05_snippet_0 LANGUAGE: tsx CODE: "use client" export default function Home() { async function handleClick() { // Send a request to our server to start the background job. // For proper error handling, refer to the quick start. // Note: This can also be a server action instead of a route handler await fetch("/api/start-email-job", { method: "POST", body: JSON.stringify({ users: ["a@gmail.com", "b@gmail.com", "c.gmail.com"] }), }) } return (
); } ---------------------------------------- TITLE: Deploying QStash Webhook Receiver on Fly.io DESCRIPTION: Commands to launch a new Fly.io app, set environment variables, and deploy the application. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/fly-io/go.mdx#2025-04-05_snippet_4 LANGUAGE: bash CODE: flyctl launch flyctl secrets set QSTASH_CURRENT_SIGNING_KEY=... flyctl secrets set QSTASH_NEXT_SIGNING_KEY=... flyctl deploy ---------------------------------------- TITLE: Retrieving URL Group with Node.js DESCRIPTION: Makes an HTTP GET request to fetch URL Group details using Node.js fetch API. Requires authentication via Bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/get.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/topics/my-url-group', { headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Implementing a QStash Job Initiator in Next.js Route Handler DESCRIPTION: A Next.js API route that receives job requests from the client, initializes the QStash client, and publishes a job to be processed asynchronously. It constructs the target API URL and forwards necessary data to QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/background-jobs.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: "YOUR_TOKEN", }); export async function POST(request: Request) { const body = await request.json(); const users: string[] = body.users; // If you know the public URL of the email API, you can use it directly const rootDomain = request.url.split('/').slice(0, 3).join('/'); const emailAPIURL = `${rootDomain}/api/send-email`; // ie: https://yourapp.com/api/send-email // Tell QStash to start the background job. // For proper error handling, refer to the quick start. await qstashClient.publishJSON({ url: emailAPIURL, body: { users } }); return new Response("Job started", { status: 200 }); } ---------------------------------------- TITLE: Testing QStash Webhook with cURL DESCRIPTION: Example cURL command to publish a message to QStash, targeting the deployed Fly.io application. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/fly-io/go.mdx#2025-04-05_snippet_5 LANGUAGE: bash CODE: curl --request POST "https://qstash.upstash.io/v2/publish/https://winter-cherry-9545.fly.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ---------------------------------------- TITLE: Response Format JSON Example DESCRIPTION: Example of JSON format specification for model output SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/llm/create.mdx#2025-04-05_snippet_1 LANGUAGE: json CODE: { "type": "json_object" } ---------------------------------------- TITLE: Fetching URL Groups with Node.js DESCRIPTION: Shows how to use the fetch API in Node.js to make a GET request to list all URL Groups. Authorization token is provided in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/list.mdx#2025-04-05_snippet_1 LANGUAGE: js CODE: const response = await fetch("https://qstash.upstash.io/v2/topics", { headers: { Authorization: "Bearer ", }, }); ---------------------------------------- TITLE: Creating a Background Job API Endpoint for Email Processing DESCRIPTION: A Next.js API route that handles the actual background job execution. This endpoint is called by QStash, processes the job (sending emails in this example), and can run long-duration tasks without blocking the main thread. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/background-jobs.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: // This is a public API endpoint that will be invoked by QStash. // It contains the logic for the background job and may take a long time to execute. import { sendEmail } from "your-email-library"; export async function POST(request: Request) { const body = await request.json(); const users: string[] = body.users; // Send emails to the users for (const user of users) { await sendEmail(user); } return new Response("Job started", { status: 200 }); } ---------------------------------------- TITLE: Delete DLQ Messages using Python DESCRIPTION: Python code using requests library to delete multiple messages from the DLQ. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/deleteMessages.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', } data = { "dlqIds": [ "11111-0", "22222-0", "33333-0" ] } response = requests.delete( 'https://qstash.upstash.io/v2/dlq', headers=headers, data=data ) ---------------------------------------- TITLE: Listing URL Groups with Python DESCRIPTION: Demonstrates using the requests library in Python to make a GET request to the QStash API endpoint for listing URL Groups. The authorization token is passed in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/list.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/topics', headers=headers ) ---------------------------------------- TITLE: Creating a QStash Schedule in TypeScript DESCRIPTION: This snippet demonstrates how to create a schedule in QStash using the TypeScript client. It sets up a schedule to publish a message to a specified URL every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "* * * * *", }); ---------------------------------------- TITLE: Setting HTTP Response in Pipedream Workflow DESCRIPTION: Code snippet demonstrating how to return a custom HTTP response in a Pipedream workflow. This is used to handle QStash message responses and enable retry functionality for failed executions. SOURCE: https://github.com/upstash/docs/blob/main/qstash/integrations/pipedream.mdx#2025-04-05_snippet_0 LANGUAGE: javascript CODE: $.respond({ status: 200 }) ---------------------------------------- TITLE: Removing an Endpoint from a URL Group with QStash in Python DESCRIPTION: This snippet shows how to remove a specific endpoint from a URL group using the QStash client. It removes the endpoint 'https://my-endpoint-1' from the 'my-url-group'. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/url-groups.mdx#2025-04-05_snippet_3 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.url_group.remove_endpoints( url_group="my-url-group", endpoints=[ {"url": "https://my-endpoint-1"}, ], ) ---------------------------------------- TITLE: Resuming a Queue using cURL in Shell DESCRIPTION: This snippet demonstrates how to resume a queue using a cURL command. It sends a POST request to the QStash API endpoint with the queue name and authorization token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/resume.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST https://qstash.upstash.io/v2/queues/queue_1234/resume \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Creating a QStash Schedule in Python DESCRIPTION: This snippet shows how to create a schedule in QStash using the Python client. It sets up a schedule to publish a message to a specified URL every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="* * * * *", ) ---------------------------------------- TITLE: Streamed Response Format for QStash LLM API Chat Completions DESCRIPTION: This snippet shows the format of a streamed response from QStash's LLM API. Each chunk contains a portion of the full response, with the final chunk including token usage statistics. The data is streamed with Server-Sent Events (SSE) format. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/llm/create.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"role":"assistant"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":"The"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":" capital"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":" of"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":" Turkey"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":" is"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":" Ankara"},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} data: {"id":"cmpl-dfc1ad80d0254c2aaf3e7775d1830c9d","object":"chat.completion.chunk","created":1717484084,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":18,"total_tokens":26,"completion_tokens":8}} data: [DONE] ---------------------------------------- TITLE: Resuming a Queue using Go with QStash Client DESCRIPTION: This snippet shows how to resume a queue using the QStash client in Go. It imports the qstash-go package, creates a client instance with the token, and calls the Resume method on the Queues object. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/resume.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: package main import ( "github.com/upstash/qstash-go" ) func main() { client := qstash.NewClient("") // error checking is omitted for brevity err := client.Queues().Resume("") } ---------------------------------------- TITLE: Scheduling to a URL Group in TypeScript DESCRIPTION: This snippet shows how to create a schedule for a URL group in QStash using the TypeScript client. It sets up a schedule to publish a message to a specified URL group every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "urlGroupName", cron: "* * * * *", }); ---------------------------------------- TITLE: Importing Required Packages for QStash Webhook Receiver in Go DESCRIPTION: Imports necessary packages for handling HTTP requests, JWT verification, and cryptographic operations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/fly-io/go.mdx#2025-04-05_snippet_1 LANGUAGE: go CODE: package main import ( "crypto/sha256" "encoding/base64" "fmt" "github.com/golang-jwt/jwt/v4" "io" "net/http" "os" "time" ) ---------------------------------------- TITLE: Retrieving URL Group with Go DESCRIPTION: Makes an HTTP GET request to fetch URL Group details using Go's http package. Requires authentication via Bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/get.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/topics/my-url-group", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Removing a QStash Queue using Node.js DESCRIPTION: This Node.js code makes a DELETE request to remove a queue from QStash. It sets the appropriate authorization header with a bearer token for authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/remove.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: const response = await fetch('https://qstash.upstash.io/v2/queue/my-queue', { method: "DELETE", headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Scheduling to a URL Group using cURL DESCRIPTION: This snippet shows how to create a schedule for a URL group in QStash using a cURL command. It sets up a schedule to publish a message to a specified URL group every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_5 LANGUAGE: bash CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/' ---------------------------------------- TITLE: Upstash-Retried Header Format Examples DESCRIPTION: Examples of the Upstash-Retried header values that QStash adds to requests sent to your API, indicating how many times the request has been retried previously. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/retry.mdx#2025-04-05_snippet_5 LANGUAGE: text CODE: Upstash-Retried: 0 // This is the first attempt Upstash-Retried: 1 // This request has been sent once before and now is the second attempt Upstash-Retried: 2 // This request has been sent twice before and now is the third attempt ---------------------------------------- TITLE: Removing a QStash Queue using Go DESCRIPTION: This Go code creates and sends a DELETE request to remove a queue from QStash. It handles potential errors and includes proper cleanup by closing the response body. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/remove.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("DELETE", "https://qstash.upstash.io/v2/queue/my-queue", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Scheduling to a Queue in TypeScript DESCRIPTION: This snippet demonstrates how to create a schedule for adding an item to a queue in QStash using the TypeScript client. It sets up a schedule to add an item to a specified queue every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_6 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "* * * * *", queueName: "yourQueueName", }); ---------------------------------------- TITLE: Referencing QStash Python SDK DESCRIPTION: This snippet shows how to reference the qstash Python SDK in code. It's a simple inline code reference to the package name. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/overview.mdx#2025-04-05_snippet_0 LANGUAGE: Python CODE: `qstash` ---------------------------------------- TITLE: Fetching a Schedule with Node.js DESCRIPTION: This code snippet shows how to retrieve a schedule using Node.js. It uses the fetch API to send a GET request to the QStash endpoint with the necessary authorization header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/get.mdx#2025-04-05_snippet_1 LANGUAGE: js CODE: const response = await fetch('https://qstash.upstash.io/v2/schedules/scd_1234', { headers: { 'Authorization': 'Bearer ' } }); ---------------------------------------- TITLE: Pausing QStash Queue using cURL DESCRIPTION: This cURL command sends a POST request to pause a specific QStash queue. It requires the queue name as a path parameter and an authorization token in the header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/pause.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST https://qstash.upstash.io/v2/queues/queue_1234/pause \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Creating Scheduled Message with cURL DESCRIPTION: This snippet demonstrates how to create a scheduled message using cURL. It sends a POST request to the QStash API with the required Authorization and Upstash-Cron headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/create.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -XPOST https://qstash.upstash.io/v2/schedules/https://www.example.com/endpoint \ -H "Authorization: Bearer " \ -H "Upstash-Cron: */5 * * * *" ---------------------------------------- TITLE: CLI Setup Output Example DESCRIPTION: Example output showing the interactive setup process when creating a new Cloudflare Worker project. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/cloudflare-workers.mdx#2025-04-05_snippet_1 LANGUAGE: text CODE: ➜ npm create cloudflare@latest Need to install the following packages: create-cloudflare@2.1.0 Ok to proceed? (y) y using create-cloudflare version 2.1.0 ╭ Create an application with Cloudflare Step 1 of 3 │ ├ In which directory do you want to create your application? │ dir ./cloudflare_starter │ ├ What type of application do you want to create? │ type "Hello World" Worker │ ├ Do you want to use TypeScript? │ yes typescript │ ├ Copying files from "hello-world" template │ ├ Do you want to use TypeScript? │ yes typescript │ ├ Retrieving current workerd compatibility date │ compatibility date 2023-08-07 │ ├ Do you want to use git for version control? │ yes git │ ╰ Application created ---------------------------------------- TITLE: Pausing QStash Queue using Python DESCRIPTION: This Python code uses the qstash library to pause a QStash queue. It requires the QStash token and queue name as parameters. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/pause.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.queue.pause("") ---------------------------------------- TITLE: Creating Scheduled Message with Go DESCRIPTION: This snippet shows how to create a scheduled message using Go. It creates a new HTTP request with the required headers and sends it to the QStash API. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/create.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("POST", "https://qstash.upstash.io/v2/schedules/https://www.example.com/endpoint", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Upstash-Cron", "*/5 * * * *") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Example JSON Response from QStash Logs API DESCRIPTION: This JSON snippet illustrates a sample response from the QStash logs API. It includes a cursor for pagination and an array of log events with details such as timestamp, message ID, state, and other relevant information. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/logs/list.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "cursor": "1686652644442-12", "events":[ { "time": "1686652644442", "messageId": "msg_123", "state": "delivered", "url": "https://example.com", "header": { "Content-Type": [ "application/x-www-form-urlencoded" ] }, "body": "bWVyaGFiYSBiZW5pbSBhZGltIHNhbmNhcg==" } ] } ---------------------------------------- TITLE: Implementing QStash Background Job Handler DESCRIPTION: Server-side implementation for publishing background jobs to QStash using the QStash client. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/vercel-nextjs.mdx#2025-04-05_snippet_5 LANGUAGE: typescript CODE: "use server" import { Client } from "@upstash/qstash" const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }) export async function startBackgroundJob() { await qstashClient.publishJSON({ url: "https://firstqstashmessage.requestcatcher.com/test", body: { hello: "world", }, }) } ---------------------------------------- TITLE: Remove URL Group using Python DESCRIPTION: Makes a DELETE request to remove a URL group using Python requests library with bearer token authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.delete( 'https://qstash.upstash.io/v2/topics/my-url-group', headers=headers ) ---------------------------------------- TITLE: Resuming a QStash Schedule in Go DESCRIPTION: This snippet shows how to resume a paused schedule using the QStash Go client. It requires the QStash Go library and a valid token, along with the schedule ID to be resumed. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/resume.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: package main import "github.com/upstash/qstash-go" func main() { client := qstash.NewClient("") // error checking is omitted for brevity err := client.Schedules().Resume("") } ---------------------------------------- TITLE: Remove URL Group using Go DESCRIPTION: Makes a DELETE request to remove a URL group using Go's http package with bearer token authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("DELETE", "https://qstash.upstash.io/v2/topics/my-url-group", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Delete Schedule using cURL DESCRIPTION: Removes a QStash schedule using a cURL DELETE request with bearer token authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/remove.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XDELETE https://qstash.upstash.io/v2/schedules/scd_123 \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Retrieving Paginated Logs in TypeScript using QStash Client DESCRIPTION: This snippet demonstrates how to retrieve all logs with pagination using a cursor. It iterates through the results, accumulating logs until there are no more pages. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/logs.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const logs = []; let cursor = null; while (true) { const res = await client.logs({ cursor }); logs.push(...res.logs); cursor = res.cursor; if (!cursor) { break; } } ---------------------------------------- TITLE: Delete Schedule using Python DESCRIPTION: Removes a QStash schedule using Python requests library with bearer token authentication. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/remove.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.delete( 'https://qstash.upstash.io/v2/schedules/scd_123', headers=headers ) ---------------------------------------- TITLE: Creating 5-Minute Interval Schedule in Python using QStash DESCRIPTION: Creates a scheduled task that runs every 5 minutes using the QStash client. Returns a schedule ID that can be used for future management of the schedule. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_0 LANGUAGE: python CODE: from qstash import QStash client = QStash("") schedule_id = client.schedule.create( destination="https://my-api...", cron="*/5 * * * *", ) print(schedule_id) ---------------------------------------- TITLE: Delete DLQ Messages using cURL DESCRIPTION: Shell command using cURL to delete multiple messages from the DLQ by providing message IDs. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/deleteMessages.mdx#2025-04-05_snippet_2 LANGUAGE: shell CODE: curl -XDELETE https://qstash.upstash.io/v2/dlq \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "dlqIds": ["11111-0", "22222-0", "33333-0"] }' ---------------------------------------- TITLE: Creating URL Group Schedule in Python using QStash DESCRIPTION: Shows how to create a schedule that targets a URL group instead of a single endpoint. The schedule will run every hour. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.create( destination="my-url-group", cron="0 * * * *", ) ---------------------------------------- TITLE: Implementing Main Function for QStash Webhook Receiver in Go DESCRIPTION: Sets up an HTTP server to handle incoming webhooks, extracts necessary information from the request, and attempts to verify the signature using both current and next signing keys. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/fly-io/go.mdx#2025-04-05_snippet_2 LANGUAGE: go CODE: func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() currentSigningKey := os.Getenv("QSTASH_CURRENT_SIGNING_KEY") nextSigningKey := os.Getenv("QSTASH_NEXT_SIGNING_KEY") tokenString := r.Header.Get("Upstash-Signature") body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = verify(body, tokenString, currentSigningKey) if err != nil { fmt.Printf("Unable to verify signature with current signing key: %v", err) err = verify(body, tokenString, nextSigningKey) } if err != nil { http.Error(w, err.Error(), http.StatusUnauthorized) return } // handle your business logic here w.WriteHeader(http.StatusOK) }) fmt.Println("listening on", port) err := http.ListenAndServe(":"+port, nil) if err != nil { panic(err) } } ---------------------------------------- TITLE: Delete DLQ Messages using Go DESCRIPTION: Go code using the standard http package to delete multiple messages from the DLQ. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/dlq/deleteMessages.mdx#2025-04-05_snippet_5 LANGUAGE: go CODE: var data = strings.NewReader(`{ "dlqIds": [ "11111-0", "22222-0", "33333-0" ] }`) req, err := http.NewRequest("DELETE", "https://qstash.upstash.io/v2/dlq", data) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Listing All Schedules in Python using QStash DESCRIPTION: Retrieves and displays a list of all schedules configured in the QStash account. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: from qstash import QStash client = QStash("") all_schedules = client.schedule.list() print(all_schedules) ---------------------------------------- TITLE: Pausing a QStash Schedule with cURL DESCRIPTION: Make a POST request to pause a QStash schedule using cURL. This requires the schedule ID and an authentication token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/pause.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST https://qstash.upstash.io/v2/schedules/scd_1234/pause \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Creating a Schedule with 5-Minute Interval in QStash using TypeScript DESCRIPTION: Initializes a QStash client and creates a schedule that runs every 5 minutes. The schedule targets the specified destination URL using a cron expression. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://my-api...", cron: "*/5 * * * *", }); ---------------------------------------- TITLE: Sending Message with Absolute Delay using cURL DESCRIPTION: This cURL command demonstrates how to send a message with an absolute delay using the Upstash-Not-Before header. The delay is specified as a Unix timestamp in seconds. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/delay.mdx#2025-04-05_snippet_3 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Not-Before: 1657104947" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ---------------------------------------- TITLE: Pausing a QStash Schedule with Node.js DESCRIPTION: Use the @upstash/qstash client library to pause a schedule in Node.js. This requires initializing the client with your QStash token and calling the pause method with the schedule ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/pause.mdx#2025-04-05_snippet_1 LANGUAGE: javascript CODE: import { Client } from "@upstash/qstash"; /** * Import a fetch polyfill only if you are using node prior to v18. * This is not necessary for nextjs, deno or cloudflare workers. */ import "isomorphic-fetch"; const c = new Client({ token: "", }); c.schedules.pause({ schedule: "" }); ---------------------------------------- TITLE: Pausing and Resuming a Schedule in QStash using TypeScript DESCRIPTION: Demonstrates how to pause a schedule, check its paused status, and resume it. This allows temporarily disabling schedules without deleting them. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_8 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const scheduleId = "my-schedule" // pause schedule await client.schedules.pause({ schedule: scheduleId }); // check if paused const result = await client.schedules.get(scheduleId); console.log(getResult.isPaused) // prints true // resume schedule await client.schedules.resume({ schedule: scheduleId }); ---------------------------------------- TITLE: Pausing a QStash Schedule with Python DESCRIPTION: Utilize the qstash Python library to pause a schedule. This requires initializing the client with your QStash token and calling the pause method with the schedule ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/pause.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.pause("") ---------------------------------------- TITLE: Listing All QStash Schedules DESCRIPTION: Examples showing how to retrieve a list of all QStash schedules using different programming languages. This is useful when you need to find a schedule ID for deletion or other operations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/delete-schedule.mdx#2025-04-05_snippet_1 LANGUAGE: shell CODE: curl \ -H 'Authorization: Bearer XXX' \ 'https://qstash.upstash.io/v2/schedules' LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.schedule.list() ---------------------------------------- TITLE: Deleting a Queue in QStash DESCRIPTION: This snippet shows how to delete a QStash queue. It initializes the QStash client with an authentication token and uses the queue's delete method to remove the specified queue. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/queues.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const queueName = "upstash-queue"; await client.queue({ queueName: queueName }).delete(); ---------------------------------------- TITLE: Pausing a QStash Schedule with Go DESCRIPTION: Use the qstash-go client library to pause a schedule in Go. This requires initializing the client with your QStash token and calling the Pause method with the schedule ID. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/pause.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: package main import "github.com/upstash/qstash-go" func main() { client := qstash.NewClient("") // error checking is omitted for brevity err := client.Schedules().Pause("") } ---------------------------------------- TITLE: Retrieving Queue Information DESCRIPTION: Examples demonstrating how to retrieve queue configuration and status information using the QStash API. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/queues.mdx#2025-04-05_snippet_2 LANGUAGE: bash CODE: curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " LANGUAGE: typescript CODE: const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.queue.get("my-queue") ---------------------------------------- TITLE: Resuming a QStash Schedule using cURL DESCRIPTION: This snippet demonstrates how to resume a paused schedule in QStash using a cURL request. It requires a valid QStash token for authentication and the ID of the schedule to resume. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/schedules/resume.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -X POST https://qstash.upstash.io/v2/schedules/scd_1234/resume \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Upserting a QStash Queue with Go DESCRIPTION: This snippet shows how to create or update a QStash queue using Go's HTTP client. It creates a new request with the appropriate headers and JSON body to interact with the QStash API. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/upsert.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: var data = strings.NewReader(`{ "queueName": "my-queue" , "parallelism" : 5, }`) req, err := http.NewRequest("POST", "https://qstash.upstash.io/v2/queues/", data) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Overwriting an Existing Schedule using cURL DESCRIPTION: This snippet shows how to overwrite an existing schedule or create a new one with a specific ID in QStash using a cURL command. It sets up a schedule with a given ID to publish a message to a specified URL every minute. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/schedules.mdx#2025-04-05_snippet_9 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -H "Upstash-Schedule-Id: existingScheduleId" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ---------------------------------------- TITLE: Removing an Endpoint from a URL Group in QStash DESCRIPTION: Removes a specific endpoint from a URL group using the urlGroups.removeEndpoints method. Requires specifying the name of the group and an array of endpoint objects to be removed. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/url-groups.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.removeEndpoints({ name: "urlGroupName", endpoints: [{ url: "https://my-endpoint-1" }], }); ---------------------------------------- TITLE: Retrieving a Queue with Python DESCRIPTION: This snippet demonstrates how to retrieve a queue using Python. It uses the requests library to send a GET request to the QStash API endpoint, specifying the queue name in the URL and including an authorization token in the headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/get.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/queue/my-queue', headers=headers ) ---------------------------------------- TITLE: Deleting a URL Group with QStash in Python DESCRIPTION: This code snippet demonstrates how to delete a URL group using the QStash client. It deletes the group named 'my-url-group'. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/url-groups.mdx#2025-04-05_snippet_4 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.url_group.delete("my-url-group") ---------------------------------------- TITLE: Resuming a Queue using Python with QStash Client DESCRIPTION: This snippet demonstrates how to resume a queue using the QStash client in Python. It imports QStash, creates a client instance with the token, and calls the resume method on the queue. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/resume.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.queue.resume("") ---------------------------------------- TITLE: Importing Required Python Modules for QStash Webhook Handling DESCRIPTION: Import statements for necessary Python modules to handle JWT decoding and signature verification in the Lambda function. SOURCE: https://github.com/upstash/docs/blob/main/qstash/quickstarts/aws-lambda/python.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: import json import os import hmac import hashlib import base64 import time import jwt ---------------------------------------- TITLE: Retrieving Schedule Details in Python using QStash DESCRIPTION: Retrieves and displays details of a specific schedule using its ID. The example shows how to access schedule properties like the cron expression. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/schedules.mdx#2025-04-05_snippet_3 LANGUAGE: python CODE: from qstash import QStash client = QStash("") schedule = client.schedule.get("") print(schedule.cron) ---------------------------------------- TITLE: List QStash Queues using cURL DESCRIPTION: API request to list all QStash queues using cURL. Requires authentication with a bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/list.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/queues \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Creating a Minute Schedule for URL Group in QStash using TypeScript DESCRIPTION: Creates a schedule that runs every minute targeting a URL group instead of a single URL. URL groups allow sending the same task to multiple destinations. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "my-url-group", cron: "* * * * *", }); ---------------------------------------- TITLE: Creating a Queue with Parallelism in QStash DESCRIPTION: This snippet demonstrates how to create a QStash queue with a parallelism value of 2 and then retrieve its details. It initializes the QStash client with an authentication token and uses the queue's upsert method to create or update the queue configuration. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/queues.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const queueName = "upstash-queue"; await client.queue({ queueName }).upsert({ parallelism: 2 }); const queueDetails = await client.queue({ queueName }).get(); ---------------------------------------- TITLE: Bulk Message Cancellation in QStash - Python DESCRIPTION: Demonstrates bulk message cancellation operations, including canceling multiple specific messages or all messages in the queue. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/messages.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: from qstash import QStash client = QStash("") # cancel more than one message client.message.cancel_many(["", ""]) # cancel all messages client.message.cancel_all() ---------------------------------------- TITLE: Retrieving a Schedule by ID in QStash using TypeScript DESCRIPTION: Fetches a specific schedule using its ID and logs the cron expression. This allows examining the configuration of a previously created schedule. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_3 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.schedules.get("scheduleId"); console.log(res.cron); ---------------------------------------- TITLE: Pausing and Resuming a Queue in QStash DESCRIPTION: This snippet illustrates how to pause and resume a QStash queue. It initializes the client, creates a queue with parallelism of 1, pauses it, retrieves its details to verify the paused state, and then resumes it. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/queues.mdx#2025-04-05_snippet_2 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const name = "upstash-pause-resume-queue"; const queue = client.queue({ queueName: name }); await queue.upsert({ parallelism: 1 }); // pause queue await queue.pause(); const queueInfo = await queue.get(); console.log(queueInfo.paused); // prints true // resume queue await queue.resume(); ---------------------------------------- TITLE: Creating or Overwriting a Schedule with Custom ID in QStash using TypeScript DESCRIPTION: Creates a schedule with a user-provided ID, which will overwrite any existing schedule with the same ID. This allows replacing schedules while maintaining the same identifier. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_5 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", scheduleId: "USER_PROVIDED_SCHEDULE_ID", cron: "* * * * *", }); ---------------------------------------- TITLE: Making GET Request to List URL Groups using curl DESCRIPTION: Demonstrates how to use curl to make a GET request to the QStash API to retrieve all URL Groups. Requires an authorization token passed in the Authorization header. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/list.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl https://qstash.upstash.io/v2/topics \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Failure Callback Response Structure DESCRIPTION: JSON structure of the failure callback response containing error status, headers, body, and metadata about the failed request. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/callbacks.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "status": 400, "header": { "key": ["value"] }, "body": "YmFzZTY0IGVuY29kZWQgcm9keQ==", "retried": 3, "maxRetries": 3, "dlqId": "1725323658779-0", "sourceMessageId": "msg_xxx", "topicName": "myTopic", "endpointName": "myEndpoint", "url": "http://myurl.com", "method": "GET", "sourceHeader": { "key": "value" }, "sourceBody": "YmFzZTY0kZWQgcm9keQ==", "notBefore": "1701198458025", "createdAt": "1701198447054", "scheduleId": "scd_xxx", "callerIP": "178.247.74.179" } ---------------------------------------- TITLE: Creating a Schedule with Timeout in QStash using TypeScript DESCRIPTION: Creates a schedule with a specified timeout value in seconds. The timeout limits how long QStash will wait for a response when calling the destination URL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/schedules.mdx#2025-04-05_snippet_7 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ url: "https://my-api...", cron: "* * * * *", timeout: "30" // 30 seconds timeout }); ---------------------------------------- TITLE: Retrieving URL Group with Python DESCRIPTION: Makes an HTTP GET request to fetch URL Group details using Python requests library. Requires authentication via Bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/get.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/topics/my-url-group', headers=headers ) ---------------------------------------- TITLE: Publishing JSON to a URL Group with Delay and Headers in Python DESCRIPTION: This code shows how to publish a JSON message to a URL group with a 3-second delay and custom headers. When publishing to a URL group, the response is an array of messages for each URL in the group. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") res = client.message.publish_json( url_group="my-url-group", body={ "hello": "world", }, headers={ "test-header": "test-value", }, delay="3s", ) # When publishing to a URL group, the response is an array of messages for each URL in the group print(res[0].message_id) ---------------------------------------- TITLE: URL Group Response Format DESCRIPTION: Example JSON response showing the structure of a URL Group including creation time, update time, name and endpoints array. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/get.mdx#2025-04-05_snippet_4 LANGUAGE: json CODE: { "createdAt": 1623345678001, "updatedAt": 1623345678001, "name": "my-url-group", "endpoints": [ { "name": "my-endpoint", "url": "https://my-endpoint.com" } ] } ---------------------------------------- TITLE: Retrieving QStash Message using Go DESCRIPTION: Shows how to retrieve a QStash message by its ID using the standard HTTP client in Go. Requires an authorization bearer token to be set in the request headers. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/messages/get.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/messages/msg_123", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Setting Request Timeout for QStash Messages in Python DESCRIPTION: This example shows how to set a timeout value for QStash when calling a URL. The timeout parameter specifies how long QStash should wait for a response before considering the request as failed. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/publish.mdx#2025-04-05_snippet_6 LANGUAGE: python CODE: from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, timeout="30s", ) ---------------------------------------- TITLE: Adding Endpoints to URL Group using Python DESCRIPTION: Example of adding multiple endpoints to a URL group using Python requests library. Shows how to structure headers and JSON payload for the API request. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/add-endpoint.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', } json_data = { 'endpoints': [ { 'name': 'endpoint1', 'url': 'https://example.com', }, { 'name': 'endpoint2', 'url': 'https://somewhere-else.com', }, ], } response = requests.post( 'https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints', headers=headers, json=json_data ) ---------------------------------------- TITLE: Rotating QStash Signing Keys in Python DESCRIPTION: This snippet demonstrates how to rotate the signing keys in QStash using the Python client. It initializes a QStash client with a token and uses the signing_key.rotate() method to generate new keys. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/py/examples/keys.mdx#2025-04-05_snippet_1 LANGUAGE: python CODE: from qstash import QStash client = QStash("") new_signing_key = client.signing_key.rotate() print(new_signing_key.current, new_signing_key.next) ---------------------------------------- TITLE: Adding Endpoints to URL Group using Go DESCRIPTION: Example of adding multiple endpoints to a URL group using Go's HTTP client. Demonstrates proper error handling and request setup. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/add-endpoint.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: var data = strings.NewReader(`{ "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] }`) req, err := http.NewRequest("POST", "https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints", data) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: List QStash Queues using Go DESCRIPTION: API request to list all QStash queues using Go standard HTTP client. Creates a new request with authorization header and executes it. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/queues/list.mdx#2025-04-05_snippet_3 LANGUAGE: go CODE: req, err := http.NewRequest("GET", "https://qstash.upstash.io/v2/queues", nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer ") resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() ---------------------------------------- TITLE: Rotating Signing Keys with cURL DESCRIPTION: This snippet demonstrates how to rotate signing keys using a cURL command. It sends a POST request to the QStash API endpoint with an authorization bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/signingKeys/rotate.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl https://qstash.upstash.io/v2/keys/rotate \ -H "Authorization: Bearer " ---------------------------------------- TITLE: Remove Endpoints using cURL DESCRIPTION: Makes a DELETE request to remove endpoints from a URL Group using cURL. Requires authorization token and accepts a JSON payload with endpoints to remove specified by name or URL. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/url-groups/remove-endpoint.mdx#2025-04-05_snippet_0 LANGUAGE: sh CODE: curl -XDELETE https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "endpoints": [ { "name": "endpoint1", }, { "url": "https://somewhere-else.com" } ] }' ---------------------------------------- TITLE: Rotating Signing Keys with Python DESCRIPTION: This snippet demonstrates how to rotate signing keys using Python. It uses the requests library to send a GET request to the QStash API endpoint with an authorization bearer token. SOURCE: https://github.com/upstash/docs/blob/main/qstash/api/signingKeys/rotate.mdx#2025-04-05_snippet_2 LANGUAGE: python CODE: import requests headers = { 'Authorization': 'Bearer ', } response = requests.get( 'https://qstash.upstash.io/v2/keys/rotate', headers=headers ) ---------------------------------------- TITLE: Creating a URL Group with Multiple Endpoints in QStash DESCRIPTION: Initializes a QStash client and creates a new URL group with two endpoints. Requires a QStash authentication token and uses the urlGroups.addEndpoints method to create the group with the specified name and endpoints. SOURCE: https://github.com/upstash/docs/blob/main/qstash/sdks/ts/examples/url-groups.mdx#2025-04-05_snippet_0 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.addEndpoints({ name: "url_group_name", endpoints: [ { url: "https://my-endpoint-1" }, { url: "https://my-endpoint-2" }, ], }); ---------------------------------------- TITLE: Creating URL Groups and Endpoints with TypeScript Client in QStash DESCRIPTION: This TypeScript code uses the @upstash/qstash client library to create URL Groups and add endpoints. It initializes a client with a QStash token and uses the urlGroups.addEndpoints method to create multiple endpoints in a single URL Group. SOURCE: https://github.com/upstash/docs/blob/main/qstash/howto/url-group-endpoint.mdx#2025-04-05_snippet_1 LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.addEndpoints({ name: "urlGroupName", endpoints: [ { name: "endpoint1", url: "https://example.com" }, { name: "endpoint2", url: "https://somewhere-else.com" }, ], }); ---------------------------------------- TITLE: Configuring QStash Retries with cURL DESCRIPTION: This example shows how to set a custom number of retries using the Upstash-Retries header with cURL when publishing a message to QStash. SOURCE: https://github.com/upstash/docs/blob/main/qstash/features/retry.mdx#2025-04-05_snippet_0 LANGUAGE: shell CODE: curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Retries: 2" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...'