### Setup Conda Environment and Install Dependencies Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime This section details the creation and activation of a Conda environment with Python 3.12, followed by the installation of project dependencies from `requirements.txt`. This ensures compatibility with Vercel's Python runtime. ```shell conda create --name vercel-django python=3.12 conda activate vercel-django pip install -r requirements.txt ``` -------------------------------- ### Setup Next.js Application and Install Apollo GraphQL Client Source: https://upstash.com/docs/redis/tutorials/coin_price_list This snippet covers the initial project setup for a Next.js application and the installation of the Apollo GraphQL client, a necessary dependency for integrating GraphQL APIs. ```bash npx create-next-app npm i @apollo/client ``` -------------------------------- ### Install Django and Upstash Redis Client Source: https://upstash.com/docs/redis/quickstarts/django Installs the necessary Python packages for Django and the Upstash Redis client. This is the first step in setting up the project environment. ```shell pip install django pip install upstash-redis ``` -------------------------------- ### Create Next.js App with Django Example Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime This command uses npx to create a new Next.js application with the Vercel Django example. It initializes the project and navigates into the project directory. ```shell npx create-next-app vercel-django --example "https://github.com/vercel/examples/tree/main/python/django" cd vercel-django ``` -------------------------------- ### Serverless Project Setup with npm Source: https://upstash.com/docs/redis/tutorials/histogram This snippet details the initial setup for a serverless project using the Serverless Framework and npm. It includes installing the framework, creating a new Node.js project, and installing necessary npm packages like ioredis and hdr-histogram-js. ```bash npm install -g serverless serverless # Follow prompts for project creation (AWS Node.js, histogram-api) npm init npm install ioredis npm install hdr-histogram-js ``` -------------------------------- ### Install Flask and Upstash Redis Client Source: https://upstash.com/docs/redis/quickstarts/flask Installs the necessary Python packages for Flask and the Upstash Redis client. These are the core dependencies for the web application. ```shell pip install flask pip install upstash-redis ``` -------------------------------- ### Install and Initialize Serverless Framework Source: https://upstash.com/docs/redis/overall/llms-txt Provides instructions for installing the Serverless Framework globally via npm and initializing a new AWS Node.js project. It demonstrates the interactive setup process for creating a new project. ```text >> serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? test-upstash Project successfully created in 'test-upstash' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` -------------------------------- ### Execute Redis Commands (Python) Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Shows examples of executing basic Redis commands like SET and GET using both synchronous and asynchronous Upstash Redis clients in Python. It assumes credentials are loaded from the environment. ```python from upstash_redis import Redis redis = Redis.from_env() def main(): redis.set("a", "b") print(redis.get("a")) ``` ```python # or for async context: from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("a", "b") print(await redis.get("a")) ``` -------------------------------- ### Django Project and App Setup Source: https://upstash.com/docs/redis/quickstarts/django Creates a new Django project and a new app within that project. It also includes instructions to add the new app to the Django settings. ```shell django-admin startproject myproject cd myproject python manage.py startapp myapp ``` -------------------------------- ### Run Flask Application Locally Source: https://upstash.com/docs/redis/quickstarts/flask Executes the Flask application from the command line. This command starts the development server, allowing you to access the application locally. ```shell python app.py ``` -------------------------------- ### Run Django Development Server Source: https://upstash.com/docs/redis/quickstarts/django Starts the Django development server, allowing you to test the web application locally. The counter will increment on each page refresh. ```shell python manage.py runserver ``` -------------------------------- ### Initialize Upstash Redis Client (Python) Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Demonstrates how to initialize both synchronous and asynchronous Upstash Redis clients in Python using direct URL and token, or by loading credentials from environment variables. ```python # for sync client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") # for async client from upstash_redis.asyncio import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` ```python # for sync use from upstash_redis import Redis redis = Redis.from_env() # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` -------------------------------- ### Install Upstash Redis Python Package Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Installs the upstash-redis Python package using pip. This is the first step to using the client in your Python projects. ```bash pip install upstash-redis ``` -------------------------------- ### Prepare Environment Variables for Local Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Copies the example environment variables file (.env.example) to .env. This is a common practice for local development setup and ensures that sensitive configuration is not committed to version control. ```bash cp .env.example .env ``` -------------------------------- ### Install Go Redis Client Library Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `go-redis/redis/v8` client library for Go applications. This command uses `go get` to download the specified package and add it to the project's module dependencies, enabling the application to interact with a Redis server. This is the sole dependency mentioned for Go API interaction. ```shell go get github.com/go-redis/redis/v8 ``` -------------------------------- ### Python Redis GET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting a key-value pair and then retrieving the value using the `GET` command in Python with the Upstash Redis client, verifying the retrieved value. ```python redis.set("key", "value") assert redis.get("key") == "value" ``` -------------------------------- ### Start AWS SAM Local API Gateway Source: https://upstash.com/docs/redis/overall/llms-txt Launches a local emulation of API Gateway and AWS Lambda using the AWS Serverless Application Model (SAM) CLI. This allows developers to test their serverless APIs locally before deploying them to the cloud. The API is typically accessible at `http://127.0.0.1:3000/`. This command requires the AWS SAM CLI to be installed. ```shell sam local start-api ``` -------------------------------- ### Install Serverless Framework CLI Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Installs the Serverless Framework globally using npm. This is a prerequisite for deploying serverless applications. ```shell npm i serverless@3.39.0 -g ``` -------------------------------- ### Create Nuxt.js Project and Install Upstash Redis Source: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis Initializes a new Nuxt.js project using the Nuxt CLI and installs the necessary Upstash Redis package. This sets up the basic project structure and dependencies for integrating Redis. ```bash npx nuxi@latest init nuxtjs-with-redis npm install @upstash/redis ``` -------------------------------- ### Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions This Dockerfile defines the steps to build a container image for a Node.js application. It installs dependencies, copies application code, and specifies the command to start the service. ```dockerfile COPY package*.json ./ RUN npm install COPY . ./ CMD [ "npm", "start" ] ``` -------------------------------- ### Initialize Next.js Project and Install ioredis Source: https://upstash.com/docs/redis/overall/llms-txt Sets up a new Next.js application and installs the 'ioredis' library, a client for interacting with Redis. This is a foundational step for projects requiring Redis integration. ```shell npx create-next-app nextjs-with-redis npm install ioredis ``` -------------------------------- ### Serverless Project Setup (Text) Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Initializes a new Serverless project for AWS Node.js. This involves running the 'serverless' command and answering prompts to define the project name and type. ```text >> serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? test-upstash Project successfully created in 'test-upstash' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` -------------------------------- ### Next.js Edge Function Example Source: https://upstash.com/docs/redis/overall/llms-txt A basic example of a Next.js Edge Function demonstrating a simple GET request handler. This serves as a starting point for using Upstash Redis with Next.js Edge Functions on Vercel. ```javascript export async function GET(request) { return new Response('Hello from Next.js Edge!'); } ``` -------------------------------- ### Install Project Dependencies Source: https://upstash.com/docs/redis/tutorials/rate-limiting Installs the project's dependencies as defined in `package.json` using npm. ```shell npm install ``` -------------------------------- ### Initialize Node.js Project and Install Dependencies Source: https://upstash.com/docs/redis/tutorials/aws_app_runner_with_redis Initializes a new Node.js project using npm and installs the 'ioredis' package, which is a robust Redis client for Node.js. This sets up the project's package.json and makes the Redis client available. ```bash npm init npm install ioredis ``` -------------------------------- ### SvelteKit TODO App with Redis Source: https://upstash.com/docs/redis/examples Demonstrates building a TODO application using SvelteKit and Upstash Redis. This example showcases how to integrate serverless Redis for data persistence in a SvelteKit project. ```javascript import TagFilters from "../../src/components/Filter.js" SvelteKit TODO App with Redis ``` -------------------------------- ### Install Laravel Installer Source: https://upstash.com/docs/redis/quickstarts/laravel Installs the Laravel installer globally using Composer. This is a prerequisite for creating new Laravel projects using the `laravel new` command. ```shell composer global require laravel/installer ``` -------------------------------- ### Slackbot with AWS Chalice and Upstash Redis Example Source: https://upstash.com/docs/redis/overall/llms-txt Guides on building a Slackbot using AWS Chalice and Upstash Redis. This example demonstrates creating serverless applications that interact with Slack and Redis. The provided snippet is a link to an article detailing the process. ```jsx Slackbot with AWS Chalice and Upstash Redis ``` -------------------------------- ### Install ioredis Client (Shell) Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Installs the ioredis package, a popular Redis client for Node.js, into the project's dependencies. ```shell npm install ioredis ``` -------------------------------- ### Run Nuxt Application and Test Redis Endpoint Source: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis Starts the Nuxt development server and provides instructions on how to test the Redis interaction endpoint. This includes running the app locally and making a `curl` request to the `/api/increment` endpoint. ```bash npm run dev curl http://localhost:3000/api/increment ``` -------------------------------- ### Install Serverless Framework Source: https://upstash.com/docs/redis/tutorials/rate-limiting Installs the Serverless Framework globally using npm. This is a prerequisite for managing and deploying serverless applications. ```shell npm i serverless -g ``` -------------------------------- ### Add Start Script to package.json Source: https://upstash.com/docs/redis/overall/llms-txt This JSON snippet shows how to add a 'start' script to the package.json file. This script allows the application to be easily started using 'npm start', which executes the index.js file with Node.js. ```json "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } ``` -------------------------------- ### Create Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/quickstarts/koyeb Defines the build process for a Node.js application using Docker. It specifies base images, installs dependencies, copies application code, and sets up the runtime environment, including port exposure and the start command. ```dockerfile FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nodejs COPY --from=deps /app/node_modules ./ COPY . . USER node EXPOSE 3000 ENV PORT 3000 CMD ["npm", "run", "start"] ``` -------------------------------- ### Read Single Stream with XREAD Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xread Reads data from a single Redis stream starting from a specified ID. This example demonstrates fetching all messages from 'mystream' starting from ID '0-0'. ```typescript const result = await redis.xread("mystream", "0-0"); ``` -------------------------------- ### Deploy React Frontend Source: https://upstash.com/docs/redis/tutorials/cloudflare_websockets_redis Commands to install dependencies and deploy the React frontend application. This includes changing to the client directory, installing packages with pnpm, and then deploying the frontend. ```bash cd client pnpm install pnpm run deploy ``` -------------------------------- ### Read Multiple Streams with XREAD Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xread Reads data from multiple Redis streams concurrently, starting from specified IDs for each stream. This example reads from 'stream1' and 'stream2', both starting from ID '0-0'. ```typescript const result = await redis.xread( ["stream1", "stream2"], ["0-0", "0-0"] ); ``` -------------------------------- ### Initialize Node.js Project and Install ioredis Source: https://upstash.com/docs/redis/overall/llms-txt Commands to initialize a new Node.js project using npm and install the 'ioredis' client library. This is a fundamental step for any Node.js application that needs to connect to Redis. ```shell npm init npm install ioredis ``` -------------------------------- ### To-Do List with Blitz.js & Redis Source: https://upstash.com/docs/redis/examples Provides an example of creating a To-Do list application using Blitz.js and Upstash Redis. This snippet highlights the integration of a full-stack framework with a serverless database. ```javascript import TagFilters from "../../src/components/Filter.js" To-Do List with Blitz.js & Redis ``` -------------------------------- ### Slackbot with Vercel and Upstash Redis Source: https://upstash.com/docs/redis/examples Demonstrates building a Slackbot using Vercel and Upstash Redis. This example highlights serverless deployment on Vercel with Redis integration for chat functionalities. ```javascript import TagFilters from "../../src/components/Filter.js" Slackbot with Vercel and Upstash Redis Slackbot with Vercel and Upstash Redis ``` -------------------------------- ### Deploy Phoenix App on Fly.io Source: https://upstash.com/docs/redis/quickstarts/elixir Deploys the configured Phoenix application to the Fly.io platform after the initial launch and configuration. This command pushes the application code and starts the services. ```bash fly deploy ``` -------------------------------- ### Python Example: Using HLEN with Upstash Redis Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hlen Demonstrates how to use the HLEN command in Python to get the number of fields in a Redis hash. It includes setting hash fields and asserting the count before and after. ```python assert redis.hlen("myhash") == 0 redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hlen("myhash") == 2 ``` -------------------------------- ### Create Serverless Project with Serverless Framework Source: https://upstash.com/docs/redis/tutorials/job_processing Initializes a new serverless project using the Serverless Framework. This command guides the user through selecting a cloud provider and project template. ```shell ➜ serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? producer Project successfully created in 'producer' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` -------------------------------- ### Get Bitfield Values (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitfield Retrieves values from specific offsets within a bitfield. This example gets unsigned 8-bit integers from offsets 0, 8, and 16, demonstrating how to read data from different parts of the bitfield. ```python redis.set("mykey", "\x05\x06\x07") result = redis.bitfield("mykey") \ .get("u8", 0) \ .get("u8", 8) \ .get("u8", 16) \ .execute() assert result == [5, 6, 7] ``` -------------------------------- ### Get Value from Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string/get Retrieves the value associated with a specified key from Upstash Redis. It handles cases where the key may not exist, returning null. This example demonstrates type safety for the retrieved value. ```typescript type MyType = { a: number; b: string; } const value = await redis.get("key"); if (!value) { // key doesn't exist } else { // value is of type MyType } ``` -------------------------------- ### Install Go Redis Client Library Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `go-redis/redis/v8` client library, the sole dependency for interacting with Redis from a Go application. ```APIDOC ## Install Go Redis Client Library ### Description Installs the `go-redis/redis/v8` client library. ### Method CLI Command ### Command `go get github.com/go-redis/redis/v8` ### Parameters None. ### Example Usage ```shell go get github.com/go-redis/redis/v8 ``` ``` -------------------------------- ### Fetch All Stream Entries with XRANGE (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrange Retrieves all entries from a Redis stream using the XRANGE command. This example demonstrates fetching all entries from 'mystream' by specifying '-' for the start ID and '+' for the end ID. ```python result = redis.xrange("mystream", "-", "+") ``` -------------------------------- ### Laravel Todo API cURL Examples Source: https://upstash.com/docs/redis/overall/llms-txt Provides a collection of cURL commands to interact with and test a Laravel Todo API, demonstrating GET, POST, PUT, and DELETE requests. ```APIDOC ## Laravel Todo API cURL Examples ### Description This section provides cURL commands to test a Laravel Todo API. It covers common operations like retrieving all todos, a specific todo, creating a new todo, updating an existing todo, and deleting a todo. ### Method GET, POST, PUT, DELETE ### Endpoint `http://todo-cache.test/api/todos` `http://todo-cache.test/api/todos/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the todo item. #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the todo item (for POST and PUT requests). ### Request Example ```bash # Get all todos curl http://todo-cache.test/api/todos # Get a specific todo curl http://todo-cache.test/api/todos/1 # Create a new todo curl -X POST http://todo-cache.test/api/todos \ -H "Content-Type: application/json" \ -d '{"title":"New Todo"}' # Update a todo curl -X PUT http://todo-cache.test/api/todos/1 \ -H "Content-Type: application/json" \ -d '{"title":"Updated Todo"}' # Delete a todo curl -X DELETE http://todo-cache.test/api/todos/1 ``` ### Response #### Success Response (200) - **data** (array) - List of todo items (for GET all). - **data** (object) - Specific todo item (for GET by ID, POST, PUT). - **message** (string) - Confirmation message (for DELETE). #### Response Example ```json // Example for GET all todos { "data": [ { "id": 1, "title": "Learn Upstash", "created_at": "...", "updated_at": "..." } ] } // Example for POST new todo { "data": { "id": 2, "title": "New Todo", "created_at": "...", "updated_at": "..." } } ``` ``` -------------------------------- ### Initialize Cloudflare Worker Project using C3 Source: https://upstash.com/docs/redis/overall/llms-txt Scaffolds a new Cloudflare Worker application using the 'create-cloudflare' (C3) tool. This command streamlines project setup and installs necessary tools like Wrangler for development. ```shell npm create cloudflare@latest ``` ```shell yarn create cloudflare@latest ``` -------------------------------- ### Start Next.js Development Server Source: https://upstash.com/docs/redis/overall/llms-txt Navigates into the 'packages/web' directory and starts the Next.js development server. This command makes the local web application accessible, typically at http://localhost:3000. ```shell cd packages/web npm run dev ``` -------------------------------- ### Install upstash-redis Client Source: https://upstash.com/docs/redis/howto/connectwithupstashredis Installs the upstash-redis JavaScript client using npm. This is the first step to integrating Redis with your application. ```bash npm install @upstash/redis ``` -------------------------------- ### DBSIZE Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the DBSIZE command to get the number of keys in a Redis database using the Upstash Redis TypeScript SDK. It requires an initialized Redis client. ```typescript const keys = await redis.dbsize(); console.log(keys) // 20 ``` -------------------------------- ### Set Up Environment Variables for Upstash Redis Source: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis Configures environment variables required to connect to the Upstash Redis database. This involves copying an example environment file and setting the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`. ```bash cp .env.example .env UPSTASH_REDIS_REST_URL="" UPSTASH_REDIS_REST_TOKEN="" ``` ```shell KV_REST_API_URL= KV_REST_API_TOKEN= ``` -------------------------------- ### Create Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/overall/llms-txt Provides a multi-stage Dockerfile for building and running a Node.js application. It includes dependency installation using npm ci, user setup for security, and exposure of the application port. ```dockerfile FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nodejs COPY --from=deps /app/node_modules ./node_modules COPY . . USER node EXPOSE 3000 ENV PORT 3000 CMD ["npm", "run", "start"] ``` -------------------------------- ### Add Development and Start Scripts to package.json Source: https://upstash.com/docs/redis/overall/llms-txt A diff snippet showing how to add `dev` and `start` scripts to a `package.json` file. The `dev` script enables debug logging for Express, while `start` runs the application normally. These are crucial for local development and deployment. ```diff { "name": "example-koyeb-upstash", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { + "dev": "DEBUG=express:* node index.js", + "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@upstash/redis": "^1.20.6", "express": "^4.18.2" } } ``` -------------------------------- ### Create SST Next.js App and Install Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/sst-v2 This snippet shows the commands to create a new SST application with a Next.js template and then install the Upstash Redis package. It assumes you have Node.js and npm installed. ```shell npx create-sst@latest --template standard/nextjs cd my-sst-app npm install npm install @upstash/redis ``` -------------------------------- ### Initialize Upstash Redis Client from Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates initializing the Upstash Redis client by loading configuration from environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`). It then performs an asynchronous `get` operation. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv()(); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` -------------------------------- ### Install Toast Component for Notifications Source: https://upstash.com/docs/redis/tutorials/notification This command installs the 'react-toastify' npm package, which is used to display notifications and announcements to the user in a non-intrusive way. ```shell npm install --save react-toastify ``` -------------------------------- ### Retrieve Upstash Redis Responses in RESP2 Format using cURL Source: https://upstash.com/docs/redis/overall/llms-txt This example uses `curl` to interact with Upstash Redis via its REST API, specifically requesting responses in the RESP2 binary format by setting the `Upstash-Response-Format` header. It includes examples for SET and GET commands and shows their expected RESP2 outputs. ```shell curl https://us1-merry-cat-32748.upstash.io/SET/foo/bar \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -H "Upstash-Reponse-Format: resp2" # +OK\r\n curl https://us1-merry-cat-32748.upstash.io/GET/foo \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -H "Upstash-Reponse-Format: resp2" # $3\r\nbar\r\n ``` -------------------------------- ### Django URL Configuration for View Source: https://upstash.com/docs/redis/quickstarts/django Maps the root URL ('') to the `index` view defined in `myapp/views.py`. This makes the counter accessible when the homepage is visited. ```python from django.urls import path from myapp import views urlpatterns = [ path('', views.index), ] ``` -------------------------------- ### Create Project Directory and Initialize npm Source: https://upstash.com/docs/redis/quickstarts/koyeb Shell commands to create a new directory for the demo application and initialize a Node.js project using npm. This sets up the basic structure for a Node.js application. ```bash mkdir example-koyeb-upstash cd example-koyeb-upstash npm init -y ``` -------------------------------- ### RANDOMKEY Usage Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to call the `randomkey()` method using the Upstash Redis client in TypeScript to get a random key from the connected database. ```APIDOC ## RANDOMKEY Command (TypeScript) ### Description Retrieve a random key from the database. ### Method RANDOMKEY ### Endpoint N/A (SDK usage) ### Parameters None ### Request Example ```typescript const key = await redis.randomkey(); ``` ### Response #### Success Response (200) - **key** (string | null) - A random key from the database, or null if the database is empty. ``` -------------------------------- ### Create Directory and Navigate Source: https://upstash.com/docs/redis/tutorials/pythonapi Creates a new directory for the project and navigates into it. This is a standard shell command for project initialization. ```shell mkdir counter-cdk && cd counter-cdk ``` -------------------------------- ### Using Render with Redis Source: https://upstash.com/docs/redis/examples Explains how to utilize Upstash Redis within applications deployed on Render. This example focuses on integrating serverless Redis with a PaaS provider. ```javascript import TagFilters from "../../src/components/Filter.js" Using Render with Redis ``` -------------------------------- ### Install FastAPI and Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/fastapi Installs the necessary Python packages for FastAPI and Upstash Redis. Ensure you have Python and pip installed. ```shell pip install fastapi pip install upstash-redis ``` -------------------------------- ### Interactive Fly.io Launch Prompt Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the interactive output of the `fly launch` command for deploying a Phoenix application. It shows the detected settings for organization, region, and resources, and prompts the user to confirm or modify these before deployment. ```shell >>> fly launch Detected a Phoenix app Creating app in /Users/examples/redix_demo We're about to launch your Phoenix app on Fly.io. Here's what you're getting: Organization: C. Arda (fly launch defaults to the personal org) Name: redix_demo (derived from your directory name) Region: Bucharest, Romania (this is the fastest region for you) App Machines: shared-cpu-1x, 1GB RAM (most apps need about 1GB of RAM) Postgres: (not requested) Redis: (not requested) Sentry: false (not requested) ? Do you want to tweak these settings before proceeding? (y/N) ``` -------------------------------- ### Deploy AWS SAM Application Source: https://upstash.com/docs/redis/overall/llms-txt Initiates a guided deployment of the AWS SAM application to AWS. The `--guided` flag prompts the user for necessary environment variables and configuration details. ```APIDOC ## Deploy AWS SAM Application ### Description Initiates a guided deployment of the AWS SAM application to AWS. The `--guided` flag prompts the user for necessary environment variables (like Upstash Redis credentials) and configuration details, simplifying the deployment process. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```shell sam deploy --guided ``` ### Response Success Response: Deployment success output from AWS SAM. Response Example: ``` Deploying stack to... ... (deployment logs) ... ``` ``` -------------------------------- ### Building a Serverless Notification API with Redis Source: https://upstash.com/docs/redis/examples Details the creation of a serverless notification API for web applications using Redis. This example showcases real-time communication patterns with a serverless backend. ```javascript import TagFilters from "../../src/components/Filter.js" Building a Serverless Notification API for Your Web Application with Redis ``` -------------------------------- ### Install Upstash Redis Client (npm) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `@upstash/redis` client library from npm. ```APIDOC ## Install Upstash Redis Client (npm) ### Description Installs the `@upstash/redis` client library for JavaScript applications. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```shell npm install @upstash/redis ``` ### Response N/A ``` -------------------------------- ### Initialize Ruby Project and Add Sidekiq Source: https://upstash.com/docs/redis/integrations/sidekiq This snippet shows the initial steps to set up a Ruby project for using Sidekiq. It involves creating a new bundle and adding the Sidekiq gem as a dependency. ```bash bundle init bundle add sidekiq ``` -------------------------------- ### Get Random Members from Sorted Set (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zrandmember Demonstrates how to use the ZRANDMEMBER command in Python to retrieve random members from a Redis sorted set. It shows examples with and without specifying the count and withscores options. ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) # "one" redis.zrandmember("myset") # ["one", "three"] redis.zrandmember("myset", 2) ``` -------------------------------- ### Install Project Dependencies with Pip Source: https://upstash.com/docs/redis/tutorials/python_realtime_chat Installs the necessary Python libraries for building the Flask and SocketIO application with Redis integration. This command ensures all required packages are available in the project environment. ```bash pip install flask flask-socketio redis ``` -------------------------------- ### Remix TODO App with Redis Source: https://upstash.com/docs/redis/examples Details the creation of a TODO application using Remix and Upstash Redis. This example demonstrates integrating a modern web framework with serverless Redis for state management. ```javascript import TagFilters from "../../src/components/Filter.js" Remix TODO App with Redis ``` -------------------------------- ### Hash Commands for Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt This Python example demonstrates various hash commands available in Upstash Redis, including deleting fields, checking existence, setting expiration, getting values, and more. ```APIDOC ## Upstash Redis Hash Commands (Python) ### Description This section provides Python examples for common Upstash Redis hash commands. ### Method Various (typically POST for mutations, GET for reads) ### Endpoint `/redis` (or similar) ### Commands & Examples **HDEL** ```python response = r.hdel("myhash", "field1") ``` **HEXISTS** ```python response = r.hexists("myhash", "field1") ``` **HEXPIRE** ```python response = r.hexpire("myhash", 60) ``` **HEXPIREAT** ```python import time response = r.hexpireat("myhash", int(time.time()) + 60) ``` **HEXPIRETIME** ```python response = r.hexpiretime("myhash") ``` **HGET** ```python response = r.hget("myhash", "field1") ``` **HGETALL** ```python response = r.hgetall("myhash") ``` **HINCRBY** ```python response = r.hincrby("myhash", "counter", 1) ``` **HINCRBYFLOAT** ```python response = r.hincrbyfloat("myhash", "floatcounter", 1.5) ``` **HKEYS** ```python response = r.hkeys("myhash") ``` **HLEN** ```python response = r.hlen("myhash") ``` **HMGET** ```python response = r.hmget("myhash", "field1", "field2") ``` **HRANDFIELD** ```python response = r.hrandfield("myhash") ``` **HPERSIST** ```python response = r.hpersist("myhash") ``` **HPEXPIRE** ```python response = r.hpexpire("myhash", 60000) ``` **HPEXPIREAT** ```python response = r.hpexpireat("myhash", int(time.time() * 1000) + 60000) ``` **HPEXPIRETIME** ```python response = r.hpexpiretime("myhash") ``` ``` -------------------------------- ### Shell: Start SST Development Server Source: https://upstash.com/docs/redis/overall/llms-txt Initiates the SST development server using `npm run dev`. This command is used to start a local development environment that monitors project changes and deploys them. ```bash npm run dev ``` -------------------------------- ### LPUSHX Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/lpushx Demonstrates the usage of the LPUSHX command in Python. It shows how to push elements to an existing list and handles the case where the list does not exist. This command is useful for conditionally adding elements to the beginning of a list. ```Python import redis # Assuming redis client is initialized as 'redis' # redis = redis.Redis(url="YOUR_UPSTASH_REDIS_URL") # Initialize the list redis.lpush("mylist", "one") # Push multiple elements to an existing list # The response will be the new length of the list assert redis.lpushx("mylist", "two", "three") == 3 # Verify the list content # The elements are added in reverse order of input assert redis.lrange("mylist", 0, -1) == ["three", "two", "one"] # Attempt to push to a non-existent list # LPUSHX returns 0 if the list does not exist assert redis.lpushx("non-existent-list", "one") == 0 ``` -------------------------------- ### Redis ZCARD Command Source: https://upstash.com/docs/redis/overall/llms-txt This entry represents the Redis ZCARD command, which is used to get the number of elements in a sorted set. No detailed API documentation or code example is provided here. ```Redis ZCARD ``` -------------------------------- ### Install @upstash/ratelimit using npm Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Installs the @upstash/ratelimit package using npm. This is the first step to adding rate limiting to your project. ```bash npm install @upstash/ratelimit ``` -------------------------------- ### TypeScript Redis BITPOS Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Provides TypeScript examples for using the `bitpos` method with the Upstash Redis client, including a basic usage scenario and an example with specified range parameters. ```typescript await redis.bitpos("key", 1); ``` ```typescript await redis.bitpos("key", 1, 5, 20); ``` -------------------------------- ### Using Upstash Redis with Remix Source: https://upstash.com/docs/redis/examples Explains the process of integrating Upstash Redis into Remix applications. This example covers basic Redis operations within the Remix framework. ```javascript import TagFilters from "../../src/components/Filter.js" Using Upstash Redis with Remix ``` -------------------------------- ### Copy Example .env File for Supabase Source: https://upstash.com/docs/redis/quickstarts/supabase Copies the example environment file for the Upstash Redis counter Supabase function. This file typically contains placeholders for Redis connection details. ```shell cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### Shell: Initialize Django Project with Vercel Template Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Django project named `vercel-django` using a Vercel example template via `npx create-next-app`. It then navigates into the project directory. ```bash npx create-next-app vercel-django --example "https://github.com/vercel/examples/tree/main/python/django" cd vercel-django ``` -------------------------------- ### Install Web Scraping Dependencies Source: https://upstash.com/docs/redis/tutorials/python_multithreading Install the necessary Python libraries for multithreaded web scraping and Redis integration. This command installs 'threading', 'requests', 'upstash-redis', and 'python-dotenv'. ```bash pip install threading requests upstash-redis python-dotenv ``` -------------------------------- ### Python Example for LPUSHX Command Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the `lpushx` command with a Python Redis client. It shows initializing a list, conditionally pushing elements, and handling non-existent keys. ```python # Initialize the list redis.lpush("mylist", "one") assert redis.lpushx("mylist", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] # Non existing key assert redis.lpushx("non-existent-list", "one") == 0 ``` -------------------------------- ### Python: Get List Length with LLEN Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to retrieve the number of elements in a Redis list using the `llen` command in Python. The example first populates a list with `rpush` and then verifies its length. ```python redis.rpush("key", "a", "b", "c") assert redis.llen("key") == 3 ``` -------------------------------- ### Set Greetings in Redis (Shell) Source: https://upstash.com/docs/redis/howto/getstartedcloudflareworkers This shell command snippet demonstrates how to set key-value pairs in an Upstash Redis database. It's used here to store different greeting messages associated with country codes. ```shell usw1-selected-termite-30690.upstash.io:30690> set GB "Ey up?" OK usw1-selected-termite-30690.upstash.io:30690> set US "Yo, what’s up?" OK usw1-selected-termite-30690.upstash.io:30690> set TR "Naber dostum?" OK usw1-selected-termite-30690.upstash.io:30690> set DE "Was ist los?" ``` -------------------------------- ### Create Serverless Project for AWS Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing a new Serverless project for an AWS Node.js application using the `serverless` CLI. This includes prompts for project setup and optional Serverless account integration. ```Shell ➜ serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? producer Project successfully created in 'producer' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` -------------------------------- ### Connect with ioredis (Node.js) Source: https://upstash.com/docs/redis/howto/connectclient Connect to Upstash Redis using the ioredis library for Node.js. This client uses the standard Redis protocol (rediss for TLS). It requires the endpoint, port, and password. The example shows setting and getting a key. ```javascript const Redis = require("ioredis"); let client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); await client.set("foo", "bar"); let x = await client.get("foo"); console.log(x); ``` -------------------------------- ### Connect to Upstash Redis using redis-cli Source: https://upstash.com/docs/redis/index This snippet demonstrates how to connect to an Upstash Redis database using the `redis-cli` tool. It shows basic commands like setting a key, getting a key, and incrementing a key's value. Ensure you have `redis-cli` installed and replace PASSWORD, ENDPOINT, and PORT with your database credentials. ```redis-cli > redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT ENDPOINT:PORT> set counter 0 OK ENDPOINT:PORT> get counter "0" ENDPOINT:PORT> incr counter (int) 1 ENDPOINT:PORT> incr counter (int) 2 ``` -------------------------------- ### Building a Survey App with Upstash Redis and Next.js Source: https://upstash.com/docs/redis/examples Provides an example of building a survey application using Next.js and Upstash Redis. This snippet showcases data collection and management in a serverless environment. ```javascript import TagFilters from "../../src/components/Filter.js" Building a Survey App with Upstash Redis and Next.js ``` -------------------------------- ### FastAPI API Setup with Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/fastapi Sets up a basic FastAPI application that connects to Upstash Redis using environment variables. It defines a root endpoint that increments a counter in Redis and returns the current count. Requires `fastapi` and `upstash-redis` to be installed. ```python from fastapi import FastAPI from upstash_redis import Redis app = FastAPI() redis = Redis.from_env() @app.get("/") def read_root(): count = redis.incr('counter') return {"count": count} ``` -------------------------------- ### Install Node.js Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Executes the npm install command to download and install project dependencies. ```APIDOC ## Install Node.js Dependencies ### Description Installs all dependencies listed in the `package.json` file. ### Method CLI Command ### Command `npm install` ### Parameters None. ### Example Usage ```shell npm install ``` ``` -------------------------------- ### Start Flask Application Server Source: https://upstash.com/docs/redis/overall/llms-txt Starts the Flask application server, making the application accessible via a web browser. ```APIDOC ## Start Flask Application Server ### Description Starts the Flask development server. ### Method CLI Command ### Command `python app.py` ### Parameters None. ### Example Usage ```bash python app.py ``` ``` -------------------------------- ### Fastly Compute Project Initialization Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Fastly Compute@Edge project. This command-line interface (CLI) tool prompts the user to select a project name, description, author, programming language (Rust, JavaScript, AssemblyScript), and a starter kit. It sets up the basic project structure for development. The output is interactive. ```shell > fastly compute init Creating a new Compute@Edge project. Press ^C at any time to quit. Name: [fastly-upstash] Description: Author: [enes@upstash.com] Language: [1] Rust [2] JavaScript [3] AssemblyScript (beta) [4] Other ('bring your own' Wasm binary) Choose option: [1] 2 Starter kit: [1] Default starter for JavaScript A basic starter kit that demonstrates routing, simple synthetic responses and overriding caching rules. https://github.com/fastly/compute-starter-kit-javascript-default [2] Empty starter for JavaScript An empty application template for the Fastly Compute@Edge environment which simply returns a 200 OK response. https://github.com/fastly/compute-starter-kit-javascript-empty Choose option or paste git URL: [1] 2 ``` -------------------------------- ### Start Local Development Server Source: https://upstash.com/docs/redis/tutorials/rate-limiting Launches the Serverless Framework development server for local testing of the deployed service. ```shell serverless dev ``` -------------------------------- ### Install isomorphic-fetch for Node.js < v18 Source: https://upstash.com/docs/redis/sdks/ts/troubleshooting If you are running on Node.js v17 or earlier, the `fetch` API is not natively supported. This snippet shows how to install the `isomorphic-fetch` package to provide a polyfill. This is necessary for platforms that do not provide their own polyfill. ```bash npm i isomorphic-fetch ``` -------------------------------- ### Initialize Django Project with Vercel Template Source: https://upstash.com/docs/redis/overall/llms-txt This command uses `npx create-next-app` to scaffold a new Django project named `vercel-django` from a Vercel example template, followed by navigating into the new project directory. ```APIDOC ## Initialize Django Project with Vercel Template ### Description This command uses `npx create-next-app` to scaffold a new Django project named `vercel-django` from a Vercel example template, followed by navigating into the new project directory. ### Method Shell commands ### Endpoint N/A ### Parameters N/A ### Request Example ```shell npx create-next-app vercel-django --example "https://github.com/vercel/examples/tree/main/python/django" cd vercel-django ``` ### Response N/A ``` -------------------------------- ### Upstash Redis String Commands (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples of common Redis string manipulation commands available through the Upstash Python client. These commands allow for setting, getting, and modifying string values. ```python append(key: str, value: str) decr(key: str) decrby(key: str, decrement: int) get(key: str) getdel(key: str) getrange(key: str, start: int, end: int) getset(key: str, value: str) incr(key: str) incrby(key: str, increment: int) incrbyfloat(key: str, increment: float) mget(keys: list[str]) mset(mapping: dict[str, str]) msetnx(mapping: dict[str, str]) set(key: str, value: str) setrange(key: str, offset: int, value: str) strlen(key: str) ``` -------------------------------- ### Create Serverless Framework Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt A command-line interaction to bootstrap a new Serverless Framework project. It guides the user through template selection (AWS Node.js HTTP API) and project naming, setting up initial scaffolding. ```shell ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · ratelimit-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · ratelimit-serverless Your new Service "ratelimit-serverless" is ready. Here are next steps: • Open Service Directory: cd ratelimit-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ``` -------------------------------- ### Python Example for MSETNX Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the MSETNX command with the Upstash Redis Python client, setting multiple key-value pairs. ```APIDOC ## Python Example for MSETNX ### Description Illustrates how to use the MSETNX command with the Upstash Redis Python client, setting multiple key-value pairs. ### Code Example ```python redis.msetnx({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" } }) ``` ``` -------------------------------- ### Configure Cloudflare Workers Wrangler TOML Source: https://upstash.com/docs/redis/howto/getstartedcloudflareworkers This TOML snippet shows how to configure the wrangler.toml file for a Cloudflare Worker. It includes environment variables for the Upstash Redis REST token and URL, which are essential for connecting to the Redis database. ```toml # wrangler.toml # existing config [vars] UPSTASH_REDIS_REST_TOKEN = "AX_sASQgODM5ZjExZGEtMmI3Mi00Mjcwk3NDIxMmEwNmNkYjVmOGVmZTk5MzQ=" UPSTASH_REDIS_REST_URL = "https://us1-merry-macaque-31458.upstash.io/" ``` -------------------------------- ### Elixir Redis Integration Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to integrate Upstash Redis with an Elixir application. It defines a module that uses the Redis client to get and set user data, encoding JSON data before setting. ```elixir defmodule MyApp.Repo do use Redis def get_user(id) do Redis.get("user:#{id}") end def set_user(id, user_data) do Redis.set("user:#{id}", Jason.encode!(user_data)) end end ``` -------------------------------- ### Launch Phoenix App on Fly.io Source: https://upstash.com/docs/redis/quickstarts/elixir Initiates the deployment process for a Phoenix application on Fly.io. This command detects the application type and prompts for configuration settings. It may initially show an error if REDIS_URL is not set, but Fly can configure it automatically. ```bash fly launch ``` -------------------------------- ### Connect to Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a Redis client for Upstash using the provided REST URL and token in a TypeScript environment. It includes a basic example of retrieving data with the `get` command and error handling. ```typescript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: 'UPSTASH_REDIS_REST_URL', token: 'UPSTASH_REDIS_REST_TOKEN' }); (async () => { try { const data = await redis.get('key'); console.log(data); } catch (error) { console.error(error); } })(); ``` -------------------------------- ### Get Substring from Redis Key (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/string/getrange Retrieves a substring from a Redis key using the GETRANGE command. This function requires a Redis client instance and takes the key, start index, and end index as arguments. It returns the specified substring. ```python redis.set("key", "Hello World") assert redis.getrange("key", 0, 4) == "Hello" ``` -------------------------------- ### RPUSHX Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/list/rpushx Demonstrates the usage of the RPUSHX command in Python. It shows how to push multiple elements to an existing list and how the command behaves when the list does not exist. ```python assert redis.rpushx("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] # Non existing key assert redis.rpushx("non-existent-list", "one") == 0 ``` -------------------------------- ### Use Redis in Fastly Compute Source: https://upstash.com/docs/redis/examples Explains how to integrate Upstash Redis into applications running on Fastly Compute@Edge. This example focuses on edge computing use cases with Redis. ```javascript import TagFilters from "../../src/components/Filter.js" Use Redis in Fastly Compute ``` -------------------------------- ### Initialize and Push Git Repository Source: https://upstash.com/docs/redis/quickstarts/koyeb This sequence of bash commands initializes a Git repository, adds all project files, commits them with a message, and sets up a remote origin to a GitHub repository. Finally, it pushes the initial commit to the main branch. Replace placeholders with your GitHub username and repository name. ```bash git init echo 'node_modules' >> .gitignore git add . git commit -m "Initial commit" git remote add origin git@github.com:/.git git push -u origin main ``` -------------------------------- ### Insert Element into Redis List (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/linsert This example demonstrates how to use the LINSERT command in TypeScript to insert an element into a Redis list. It first populates a list and then inserts 'x' before 'b'. Ensure you have the Upstash Redis client library installed and configured. ```typescript await redis.rpush("key", "a", "b", "c"); await redis.linsert("key", "before", "b", "x"); ``` -------------------------------- ### Install Upstash Rate Limit Library (Python) Source: https://upstash.com/docs/redis/sdks/ratelimit-py/gettingstarted Installs the upstash-ratelimit Python package using pip. This is the first step to using the rate limiting features. ```bash pip install upstash-ratelimit ``` -------------------------------- ### Using Upstash Redis as a Session Store for Remix Source: https://upstash.com/docs/redis/examples Demonstrates how to use Upstash Redis as a session store for Remix applications. This example focuses on managing user sessions securely and scalably. ```javascript import TagFilters from "../../src/components/Filter.js" Using Upstash Redis as a Session Store for Remix ``` -------------------------------- ### Instantiate Redis Client in Deno Source: https://upstash.com/docs/redis/sdks/ts/deployment Shows how to initialize a Redis client for Deno environments, including Deno Deploy and Netlify Edge. It demonstrates instantiation using environment variables or direct URL and token. ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: , token: , }) // or const redis = Redis.fromEnv(); ``` -------------------------------- ### Install BullMQ and Upstash Redis Source: https://upstash.com/docs/redis/integrations/bullmq Install the necessary packages for BullMQ and Upstash Redis using npm. This command fetches and installs the latest versions of both libraries, making them available for use in your Node.js project. ```bash npm install bullmq upstash-redis ``` -------------------------------- ### Install Upstash Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `@upstash/redis` npm package, which is the client library required for interacting with Upstash Redis. ```APIDOC ## Install Upstash Redis Client ### Description This command installs the `@upstash/redis` npm package, which is the client library necessary for interacting with Upstash Redis services. ### Method N/A (Installation command) ### Endpoint N/A (Installation command) ### Parameters N/A (Installation command) ### Request Example ```bash npm install @upstash/redis ``` ### Response N/A (Installation command) ``` -------------------------------- ### Initialize Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new directory for a project and then navigates into that directory. This is a fundamental step for setting up a new workspace for development. ```shell mkdir app_runner_example cd app_runner_example ``` -------------------------------- ### Get List Length using LLEN in Python Source: https://upstash.com/docs/redis/overall/llms-txt This Python example demonstrates how to use the `llen` command with a Redis client. It first populates a list using `rpush` and then asserts the correct length using `llen`. ```APIDOC ## Get List Length using LLEN in Python ### Description This Python example demonstrates how to use the `llen` command with a Redis client. It first populates a list using `rpush` and then asserts the correct length using `llen`. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```python redis.rpush("key", "a", "b", "c") assert redis.llen("key") == 3 ``` ### Response #### Success Response No explicit response, but the assertion `redis.llen("key") == 3` should pass if the list length is correctly reported. #### Response Example N/A ``` -------------------------------- ### Session Management on Google Cloud Run with Serverless Redis Source: https://upstash.com/docs/redis/examples Demonstrates session management on Google Cloud Run using Upstash Redis. This example highlights how to handle user sessions in a serverless container environment. ```javascript import TagFilters from "../../src/components/Filter.js" Session Management on Google Cloud Run with Serverless Redis ``` -------------------------------- ### Count Set Bits in Range with BITCOUNT (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/bitmap/bitcount Illustrates using the BITCOUNT command in Upstash Redis to count set bits within a specific byte range of a binary string. This example specifies both start and end arguments for the range. ```typescript const bits = await redis.bitcount(key, 5, 10); ``` -------------------------------- ### Run the Python URL Shortener Application Source: https://upstash.com/docs/redis/tutorials/python_url_shortener Executes the Python script to demonstrate the URL shortening functionality. This command will start the application, shorten a sample URL, and print the resulting short URL and its original counterpart. ```shell python url_shortener.py ``` -------------------------------- ### Manually Initialize Redis Client Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Demonstrates how to manually initialize the Redis client by providing the URL and token directly, instead of relying on environment variables. This is useful when environment variables are stored with different names or in a custom configuration. ```typescript new Redis({ url: "https://****.upstash.io", token: "********", }); ``` -------------------------------- ### Read Stream with Count Limit using XREAD Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xread Reads data from a Redis stream with a specified limit on the number of messages returned per stream. This example reads from 'mystream' starting from ID '0-0', but limits the results to 2 messages. ```typescript const result = await redis.xread("mystream", "0-0", { count: 2 }); ``` -------------------------------- ### Next.js Authentication with NextAuth and Serverless Redis Source: https://upstash.com/docs/redis/examples Demonstrates how to integrate NextAuth for authentication in a Next.js application, using Upstash Redis as the session store. This example highlights secure and scalable authentication patterns. ```javascript import TagFilters from "../../src/components/Filter.js" Next.js Authentication with NextAuth and Serverless Redis ``` -------------------------------- ### TypeScript: Get String Length with Redis STRLEN Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates retrieving the length of a string value associated with a Redis key using the `STRLEN` command in TypeScript. The example covers setting a string and then logging its length. ```typescript await redis.set("key", "helloworld") const length = await redis.strlen("key") console.log(length) // 10 ``` -------------------------------- ### Install Upstash Redis Client via Package Managers Source: https://upstash.com/docs/redis/sdks/ts/getstarted Install the Upstash Redis client for Node.js environments using npm, yarn, or pnpm. This provides an npm-compatible package. ```bash npm install @upstash/redis ``` ```bash yarn add @upstash/redis ``` ```bash pnpm add @upstash/redis ``` -------------------------------- ### Get Set Size with SCARD (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/set/scard The SCARD command returns the number of members in a set. It takes the key of the set as an argument. The response is an integer representing the count. This example demonstrates adding members and then retrieving the set's size. ```python redis.sadd("key", "a", "b", "c"); assert redis.scard("key") == 3 ``` -------------------------------- ### Connect to Upstash Redis with Redisson and Perform Basic Operations Source: https://upstash.com/docs/redis/overall/llms-txt This Java example illustrates initializing the Redisson client to connect to an Upstash Redis instance using a password and endpoint. It performs basic `put` and `get` operations on a distributed map. ```java public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") // use "rediss://" for SSL connection .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ``` -------------------------------- ### SUBSTR: Get Substring of a String (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string Returns a substring of the string value stored at a key, from a specified start offset to an end offset. If the key does not exist, an empty string is returned. This command is useful for extracting parts of string data. ```typescript const substring = await redis.substr("mykey", 2, 5); ``` -------------------------------- ### Install FastAPI and Upstash Redis Libraries Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages, FastAPI for web framework and upstash-redis for Redis client, using the pip package manager. ```APIDOC ## Install Python Libraries ### Description Installs FastAPI and the upstash-redis Python client. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```shell pip install fastapi pip install upstash-redis ``` ### Response N/A ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/redis/tutorials/aws_app_runner_with_redis Creates a new directory for the project. This is a standard command-line operation for initializing a new project structure. ```bash mkdir app_runner_example cd app_runner_example ``` -------------------------------- ### Start AWS SAM Local API Gateway Source: https://upstash.com/docs/redis/overall/llms-txt Launches a local emulation of API Gateway and AWS Lambda for testing serverless APIs locally. ```APIDOC ## Start AWS SAM Local API Gateway ### Description Launches a local emulation of API Gateway and AWS Lambda to test serverless APIs. ### Method CLI Command ### Command `sam local start-api` ### Parameters None directly. ### Access URL `http://127.0.0.1:3000/` (or the endpoint defined in your SAM template) ### Example Usage ```shell sam local start-api ``` ``` -------------------------------- ### BITCOUNT Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitcount Demonstrates how to use the BITCOUNT command in Redis with Python. It shows setting bits and then counting them, both with and without specifying a range. This command is useful for bit-level operations on binary data. ```python redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) redis.setbit("mykey", 9, 1) # With range assert redis.bitcount("mykey", 0, 10) == 3 # Without range assert redis.bitcount("mykey") == 3 ``` -------------------------------- ### Redis ZINTER Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zinter Demonstrates how to use the ZINTER command in Python to find the intersection of two sorted sets. This example shows a basic intersection without scores or weights. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinter(["key1", "key2"]) assert result == ["c"] ``` -------------------------------- ### Trim List with LTRIM (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/ltrim Trims a Redis list to a specified range of elements. It takes the key of the list, a start index, and an end index as arguments. The original list is modified in place. This example demonstrates pushing elements and then trimming the list. ```typescript await redis.lpush("key", "a", "b", "c", "d"); await redis.ltrim("key", 1, 2); // the list is now ["b", "c"] ``` -------------------------------- ### Next.js App Router Project Initialization and Upstash Redis Installation Source: https://upstash.com/docs/redis/overall/llms-txt Provides the shell commands to create a new Next.js application using the App Router and install the `@upstash/redis` package. ```APIDOC ## Next.js App Router Project Initialization and Upstash Redis Installation ### Description This snippet provides the shell commands to create a new Next.js application using the App Router. It also includes the command to install the `@upstash/redis` package, which is necessary for interacting with Upstash Redis. ### Method Shell Commands ### Endpoint N/A ### Parameters None ### Request Example ```shell npx create-next-app@latest cd my-app npm install @upstash/redis ``` ### Response Success Response: Shell command execution output. Response Example: ``` # Example output after running the commands Creating a new Next.js app in /path/to/my-app. ... (installation logs) ... ``` ``` -------------------------------- ### Deploying Serverless Function Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Command to deploy the configured serverless application to AWS. Ensure you have the Serverless Framework installed and configured with AWS credentials. ```shell serverless deploy ``` -------------------------------- ### Use Redis in Cloudflare Workers Source: https://upstash.com/docs/redis/examples Provides instructions on how to use Upstash Redis within Cloudflare Workers. This example focuses on serverless edge computing with Redis integration. ```javascript import TagFilters from "../../src/components/Filter.js" Use Redis in Cloudflare Workers ``` -------------------------------- ### Read from multiple streams using XREADGROUP (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xreadgroup This Python example shows how to read messages from multiple streams concurrently using the XREADGROUP command. It takes the group, consumer, and a dictionary of streams, where each stream can have a specific starting ID (e.g., '>' for new messages or '0-0' for all messages). ```python result = redis.xreadgroup("mygroup", "consumer1", {"stream1": ">", "stream2": "0-0"}) ``` -------------------------------- ### SMEMBERS Command API (Python Example) Source: https://upstash.com/docs/redis/overall/llms-txt Comprehensive documentation and example for the Redis `SMEMBERS` command, which retrieves all members from a specified set. ```APIDOC ## SMEMBERS ### Description Return all the members of a set. ### Method GET ### Endpoint `/set/{key}/members` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the set. ### Request Example ```python redis.sadd("set", "a", "b", "c") redis.smembers("set") ``` ### Response #### Success Response (200) - **members** (set[str]) - Required - The members of the set. #### Response Example ```json ["a", "b", "c"] ``` ``` -------------------------------- ### Copy .env file for Supabase Function Source: https://upstash.com/docs/redis/overall/llms-txt Copies the example environment file to the active .env file for the Supabase function, preparing it for configuration with Redis credentials. ```APIDOC ## Copy .env file for Supabase Function ### Description Copies the example environment file to the active `.env` file for a Supabase function to configure Redis credentials. ### Command ```shell cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env ``` ``` -------------------------------- ### Get Multiple Random Set Members with SRANDMEMBER (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/set/srandmember Illustrates fetching multiple random members from a Redis set using the SRANDMEMBER command in Python. This example specifies a count to retrieve more than one member, returning them as an array. It requires a Redis client instance. ```python redis.sadd("myset", "one", "two", "three") assert redis.srandmember("myset", 2) in {"one", "two", "three"} ``` -------------------------------- ### Remix on Cloudflare with Upstash Redis Source: https://upstash.com/docs/redis/examples Shows how to deploy Remix applications on Cloudflare Workers and integrate with Upstash Redis. This example focuses on building fast, serverless web applications at the edge. ```javascript import TagFilters from "../../src/components/Filter.js" Remix on Cloudflare with Upstash Redis ``` -------------------------------- ### Application Run: Start SST Development Server Source: https://upstash.com/docs/redis/overall/llms-txt Initiates the SST development server, which monitors your project for changes and automatically deploys updates to your local AWS environment or mock services. ```APIDOC ## Application Run: Start SST Development Server ### Description Initiates the SST development server, which monitors your project for changes and automatically deploys updates to your local AWS environment or mock services. ### Method Shell command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell npm run dev ``` ### Response N/A ``` -------------------------------- ### Get Substring of Value using GETRANGE (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string/getrange Retrieves a substring from a Redis value using the GETRANGE command. This function requires the Redis client instance, the key of the string value, and the start and end indices for the substring. It returns the extracted substring. ```typescript const substring = await redis.getrange("key", 2, 4); ``` -------------------------------- ### Connect with Jedis (Java) Source: https://upstash.com/docs/redis/howto/connectclient Connect to Upstash Redis using the Jedis library for Java. This client requires the endpoint, port, and password, with TLS enabled by default. The example shows setting and getting a key. Note that Jedis does not offer command-level retry configuration by default. ```java Jedis jedis = new Jedis("YOUR_ENDPOINT", "YOUR_PORT", true); jedis.auth("YOUR_PASSWORD"); jedis.set("foo", "bar"); String value = jedis.get("foo"); System.out.println(value); ``` -------------------------------- ### Slackbot with AWS Chalice and Upstash Redis Source: https://upstash.com/docs/redis/examples Details the creation of a Slackbot using AWS Chalice and Upstash Redis. This example demonstrates serverless backend development for chat applications. ```javascript import TagFilters from "../../src/components/Filter.js" Slackbot with AWS Chalice and Upstash Redis ``` -------------------------------- ### Cloudflare Worker with Upstash Redis (JavaScript) Source: https://upstash.com/docs/redis/howto/getstartedcloudflareworkers This JavaScript code snippet defines a Cloudflare Worker that fetches a greeting from Upstash Redis based on the client's IP country. It uses the '@upstash/redis/cloudflare' SDK and retrieves credentials from environment variables. ```javascript // src/index.js import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env) { const redis = Redis.fromEnv(env); const country = request.headers.get("cf-ipcountry"); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response("Hello!"); }, }; ``` -------------------------------- ### Initialize Nuxt.js Project (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new Nuxt.js application using the nuxi CLI. This command scaffolds a basic Nuxt.js project, preparing it for further development. ```bash npx nuxi@latest init nuxtjs-with-redis ``` -------------------------------- ### TypeScript Example for ZREMRANGEBYRANK Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the ZREMRANGEBYRANK command with the Upstash Redis client in TypeScript. ```APIDOC ## TypeScript Example for ZREMRANGEBYRANK ### Description An example demonstrating how to use the ZREMRANGEBYRANK command with the Upstash Redis client in TypeScript. ### Code Example ```typescript await redis.zremrangebyrank("key", 4, 20) ``` ``` -------------------------------- ### ZSCAN Sorted Set Scan with Match (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zscan Illustrates scanning a sorted set in Upstash Redis using the ZSCAN command with a match pattern. The example first populates the set with ZADD and then performs a ZSCAN operation filtering members that start with 'a'. The results include the new cursor and the matching members. ```typescript await redis.zadd("key", { score: 1, member: "a" }, { score: 2, member: "ab" }, { score: 3, member: "b" }, { score: 4, member: "c" }, { score: 5, member: "d" }, ) const [newCursor, members] = await redis.zscan("key", 0, { match: "a*"}); console.log(newCursor); // likely `0` since this is a very small set console.log(members); // ["a", "ab"] ``` -------------------------------- ### FLUSHALL Command Python Examples Source: https://upstash.com/docs/redis/overall/llms-txt Provides Python code examples for using the `flushall` method with the Upstash Redis client, demonstrating both synchronous and asynchronous calls. ```APIDOC ## FLUSHALL Command Python Examples ### Description These Python examples demonstrate how to use the `flushall` method with the Upstash Redis client. The `flushall` command removes all keys from the currently selected database. Examples include both synchronous and asynchronous execution. ### Method Not Applicable (SDK method) ### Endpoint Not Applicable (SDK method) ### Parameters - **flush_type** (string) - Optional - Can be set to `"ASYNC"` to perform the flush in the background. ### Request Example ```python # Synchronous FLUSHALL redis.flushall() # Asynchronous FLUSHALL redis.flushall(flush_type="ASYNC") ``` ### Response Not Applicable (SDK method) ``` -------------------------------- ### TypeScript Example: Using redis.touch Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the `redis.touch` method in TypeScript to update the last access time for multiple keys. ```APIDOC ## TypeScript Example: Using redis.touch ### Description An example demonstrating how to use the `redis.touch` method in TypeScript to update the last access time for multiple keys. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```ts await redis.touch("key1", "key2", "key3"); ``` ### Response #### Success Response Returns the number of keys that had their expiry set. #### Response Example ```json 3 ``` ``` -------------------------------- ### Install upstash-redis-dump CLI tool Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `upstash-redis-dump` command-line interface globally using npm, which is required for exporting and importing Redis data. ```APIDOC ## Install upstash-redis-dump CLI tool ### Description Installs the `upstash-redis-dump` command-line interface globally using npm, which is required for exporting and importing Redis data. ### Command ```bash npm install -g upstash-redis-dump ``` ``` -------------------------------- ### Flask Application with Upstash Redis Counter Source: https://upstash.com/docs/redis/quickstarts/flask A simple Flask application that uses Upstash Redis to increment a counter on each homepage visit. It initializes the Redis connection from environment variables and defines a route to handle counter increments. ```python from flask import Flask from upstash_redis import Redis app = Flask(__name__) redis = Redis.from_env() @app.route('/') def index(): count = redis.incr('counter') return f'Page visited {count} times.' if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Python: Automatically Claim Pending Stream Messages with XAUTOCLAIM Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xautoclaim This Python code snippet demonstrates how to use the `xautoclaim` command to automatically claim pending messages from a Redis stream. It shows a basic usage and an advanced example with `count` and `justid` options. The function requires the stream key, consumer group name, the consumer name that will claim the messages, the minimum idle time in milliseconds, and the starting stream ID. It returns the next start ID for pagination, claimed messages, and deleted message IDs. ```python import redis redis_client = redis.Redis(host='YOUR_REDIS_HOST', port=6379, password='YOUR_REDIS_PASSWORD') # Auto-claim messages that have been idle for more than 60 seconds result = redis_client.xautoclaim( "mystream", "mygroup", "consumer1", 60000, # 60 seconds start="0-0" ) print(f"Basic claim result: {result}") # With count and justid result_justid = redis_client.xautoclaim( "mystream", "mygroup", "consumer1", 60000, start="0-0", count=5, justid=True ) print(f"Claim result with count and justid: {result_justid}") ``` -------------------------------- ### Install ioredis Redis Client for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `ioredis` client library, a high-performance Redis client for Node.js, as a project dependency, enabling interaction with Upstash Redis from Lambda functions. ```shell npm install ioredis ``` -------------------------------- ### Get Stream Length using Python with Upstash Redis Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xlen The XLEN command returns the number of entries in a Redis stream. It takes the stream key as an argument and returns an integer representing the count. If the stream does not exist, it returns 0. This example demonstrates its usage with Python. ```python result = redis.xlen("mystream") ``` -------------------------------- ### SUNIONSTORE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `SUNIONSTORE` command in Python. This example first populates two sets and then performs a union operation, storing the result in a new destination set. ```APIDOC ## SUNIONSTORE Command (Python) ### Description Performs a union of two sets and stores the result in a destination set. ### Method Client Method Call ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); redis.sunionstore("destination", "set1", "set2") ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements in the newly created destination set. ``` -------------------------------- ### Install Laravel API Package Source: https://upstash.com/docs/redis/tutorials/laravel_caching Installs the necessary package for creating API resources within the Laravel application. This command is part of the process for building the API endpoints. ```shell php artisan install:api ``` -------------------------------- ### Instantiate Redis Client in Node.js/Browser Source: https://upstash.com/docs/redis/sdks/ts/deployment Demonstrates how to create a Redis client instance for Node.js and browser environments. It shows initialization using environment variables or direct URL and token. Supports older Node.js versions with a specific import. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ```typescript import { Redis } from "@upstash/redis/with-fetch"; ``` -------------------------------- ### Node.js AWS Lambda Function with ioredis Source: https://upstash.com/docs/redis/howto/getstartedawslambda This Node.js code snippet demonstrates how to connect to an Upstash Redis database from an AWS Lambda function using the ioredis client. It sets a key-value pair and retrieves it. Ensure you replace placeholder credentials with your actual Redis URL. ```javascript var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.handler = async (event) => { await client.set("foo", "bar"); let result = await client.get("foo"); let response = { statusCode: 200, body: JSON.stringify({ result: result, }), }; return response; }; ``` -------------------------------- ### PERSIST Command TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript code example demonstrating how to use the `persist` method with the Upstash Redis client. ```APIDOC ## PERSIST Command TypeScript Example ### Description This example shows how to use the `persist` method from the Upstash Redis client in TypeScript. This command is used to remove the time-to-live (TTL) associated with a key, making it persistent. ### Method Not Applicable (SDK method) ### Endpoint Not Applicable (SDK method) ### Parameters Not Applicable (SDK method) ### Request Example ```ts await redis.persist(key); ``` ### Response Not Applicable (SDK method) ``` -------------------------------- ### Fastly Project Initialization Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Fastly Compute@Edge project, prompting for language and starter kit selection. ```APIDOC ## Fastly Compute Init ### Description Initializes a new Fastly Compute@Edge project. ### Method CLI Command ### Command `fastly compute init` ### Parameters None directly, prompts user for input. ### Prompts - **Name**: Name of the project. - **Description**: Project description. - **Author**: Author's email. - **Language**: Choice of programming language (Rust, JavaScript, etc.). - **Starter kit**: Choice of starter kit (default, empty, or custom URL). ### Example Usage ```shell > fastly compute init ``` ``` -------------------------------- ### AWS Lambda Function for Upstash Redis (Node.js) Source: https://upstash.com/docs/redis/howto/getstartedawslambda This Node.js code snippet demonstrates an AWS Lambda function designed to insert data into an Upstash Redis database. It requires the 'redis' package and expects a JSON event payload with 'key' and 'value' properties. ```javascript const redis = require("redis"); exports.handler = async (event) => { const client = redis.createClient({ url: process.env.REDIS_URL }); client.on('error', (err) => console.log('Redis Client Error', err)); await client.connect(); const { key, value } = event; if (!key || !value) { return { statusCode: 400, body: JSON.stringify('Key and value are required.') }; } try { await client.set(key, value); await client.quit(); return { statusCode: 200, body: JSON.stringify(`Successfully set key: ${key} with value: ${value}`) }; } catch (err) { console.error(err); await client.quit(); return { statusCode: 500, body: JSON.stringify('Error setting value in Redis.') }; } }; ``` -------------------------------- ### Create new Laravel project using Composer Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new Laravel application named 'example-app' directly via Composer, offering an alternative to installing the Laravel CLI. The command also navigates into the newly created project directory. ```APIDOC ## Create new Laravel project using Composer ### Description Creates a new Laravel application named 'example-app' directly via Composer, offering an alternative to installing the Laravel CLI. The command also navigates into the newly created project directory. ### Method Shell commands ### Endpoint N/A ### Parameters N/A ### Request Example ```shell composer create-project laravel/laravel example-app cd example-app ``` ### Response N/A ``` -------------------------------- ### Get List Elements with LRANGE (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/lrange Retrieves a range of elements from a Redis list using the LRANGE command. This function requires the 'redis' client object and takes the list key, start index, and end index as arguments. It returns an array of elements within the specified range. ```typescript await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` -------------------------------- ### TypeScript Example for JSON.OBJKEYS Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the `redis.json.objkeys` method in TypeScript to retrieve keys from a JSON object at a specified path. ```APIDOC ## TypeScript Example for JSON.OBJKEYS ### Description An example demonstrating how to use the `redis.json.objkeys` method in TypeScript to retrieve keys from a JSON object at a specified path. ### Code Example ```typescript const keys = await redis.json.objkeys("key", "$.path"); ``` ``` -------------------------------- ### SMOVE Command Example in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/set/smove Demonstrates how to use the SMOVE command to move a member from one Redis set to another. It shows the initial state of the sets, the execution of the SMOVE command, and the resulting state of the sets. ```typescript await redis.sadd("original", "a", "b", "c"); const moved = await redis.smove("original", "destination", "a"); // moved: 1 // original: ["b", "c"] // destination: ["a"] ``` -------------------------------- ### Global Cache for Netlify Graph with Upstash Redis Source: https://upstash.com/docs/redis/examples Explains how to implement a global cache for Netlify Graph using Upstash Redis. This example focuses on performance optimization for serverless GraphQL APIs. ```javascript import TagFilters from "../../src/components/Filter.js" Global Cache for Netlify Graph with Upstash Redis ``` -------------------------------- ### Redis GETSET Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/string/getset This Python code snippet demonstrates how to use the GETSET command with Upstash Redis. It first sets a key with an initial value and then uses GETSET to retrieve that value while simultaneously updating the key with a new value. The assertion verifies that the correct old value was returned. ```python redis.set("key", "old-value") assert redis.getset("key", "newvalue") == "old-value" ``` -------------------------------- ### Python Example for SISMEMBER Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the SISMEMBER command in Python. This example first adds elements to a Redis set and then asserts the presence of a specific member using `sismember`. ```APIDOC ## Python Example for SISMEMBER ### Description Illustrates how to use the SISMEMBER command in Python. This example first adds elements to a Redis set and then asserts the presence of a specific member using `sismember`. ### Code Example ```python redis.sadd("set", "a", "b", "c") assert redis.sismember("set", "a") == True ``` ``` -------------------------------- ### Serverless Redis Caching for Strapi Source: https://upstash.com/docs/redis/examples Illustrates how to implement serverless Redis caching for Strapi, a headless CMS. This example focuses on improving performance by caching API responses using Upstash Redis. ```javascript import TagFilters from "../../src/components/Filter.js" Serverless Redis Caching for Strapi ``` -------------------------------- ### JavaScript: Increment Redis Counter in Google Cloud Function Source: https://upstash.com/docs/redis/howto/getstartedgooglecloudfunctions This JavaScript code snippet demonstrates how to initialize an ioredis client and use it to increment a counter in an Upstash Redis database within a Google Cloud Function. It assumes the Redis client is already configured and available. ```javascript var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.helloGET = async (req, res) => { let count = await client.incr("counter"); res.send("Page view:" + count); }; ``` -------------------------------- ### Connect and Use Upstash Redis in Next.js Source: https://upstash.com/docs/redis/howto/vercelintegration Demonstrates how to initialize the Upstash Redis client using environment variables and perform basic set/get operations within a Next.js API route. Requires the '@upstash/redis' package. ```typescript import { Redis } from "@upstash/redis"; import { type NextRequest, NextResponse } from "next/server"; const redis = Redis.fromEnv(); export const POST = async (request: NextRequest) => { await redis.set("foo", "bar"); const bar = await redis.get("foo"); return NextResponse.json({ body: `foo: ${bar}`, }); } ``` -------------------------------- ### Update requirements.txt for Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime This file lists the Python dependencies for the project. The `upstash-redis` package is added to enable Redis integration. ```txt Django==4.1.3 upstash-redis ``` -------------------------------- ### Install Flask and Upstash Redis Python Libraries Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages: Flask, a micro web framework, and `upstash-redis`, the client library for interacting with Upstash Redis databases. ```APIDOC ## Install Flask and Upstash Redis Python Libraries ### Description This command installs the necessary Python packages: Flask, a micro web framework, and `upstash-redis`, the client library for interacting with Upstash Redis databases. These are essential dependencies for building the web application. ### Commands ```bash pip install flask pip install upstash-redis ``` ``` -------------------------------- ### Python LPOS Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates finding elements in a Redis list using the LPOS command in Python. Includes examples for finding the first occurrence, subsequent occurrences using rank, and multiple occurrences using count. Requires a Redis client instance. ```python redis.rpush("key", "a", "b", "c"); assert redis.lpos("key", "b") == 1 ``` ```python redis.rpush("key", "a", "b", "c", "b"); assert redis.lpos("key", "b", rank=2) == 3 ``` ```python redis.rpush("key", "a", "b", "b") assert redis.lpos("key", "b", count=2) == [1, 2] ``` -------------------------------- ### Configure Upstash Strapi Ratelimit Plugin Source: https://upstash.com/docs/redis/overall/llms-txt Configuration examples for the Upstash Strapi Ratelimit plugin. This includes enabling the plugin, setting up environment variables for token and URL, and defining a rate limiting strategy. ```typescript export default () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s" } } ], prefix: "@strapi" } } }); ``` ```javascript module.exports = () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s" } } ], prefix: "@strapi" } } }); ``` -------------------------------- ### LPUSHX Example with Existing List (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/lpushx Demonstrates using the LPUSHX command to push elements to the head of an existing list in Upstash Redis. It shows the expected return value representing the new list length. ```typescript await redis.lpush("key", "a", "b", "c"); const length = await redis.lpushx("key", "d"); console.log(length); // 4 ``` -------------------------------- ### Create New Laravel Project Source: https://upstash.com/docs/redis/overall/llms-txt Commands to initialize a new Laravel application and navigate into the project directory. ```APIDOC ## Create and Navigate Laravel Project ### Description Initializes a new Laravel project and changes the directory into it. ### Commands - **laravel new [project-name]**: Creates a new Laravel project with the specified name. - **cd [project-name]**: Changes the current directory to the specified project. ### Example ```bash laravel new todo-cache cd todo-cache ``` ``` -------------------------------- ### Basic Redis Command Execution (GET) Source: https://upstash.com/docs/redis/features/restapi Execute a Redis GET command using the REST API. The command and its arguments are appended to the base URL. ```APIDOC ## GET / ### Description Retrieves the value associated with a given key from the Redis database. ### Method GET ### Endpoint `/` ### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```shell curl https://YOUR_REDIS_ENDPOINT/get/mykey \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **result** (string or null) - The value of the key, or null if the key does not exist. #### Response Example ```json { "result": "myvalue" } ``` ``` -------------------------------- ### Google Cloud Run Deployment Console Output Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates typical console output after a successful Google Cloud Run deployment. It shows stages like deploying, revision creation, traffic routing, IAM policy updates, and the final service URL. ```Text Deploying container to Cloud Run service [cloud-run-sessions] in project [cloud-run-sessions] region [us-central1] ✔ Deploying... Done. ✔ Creating Revision... ✔ Routing traffic... ✔ Setting IAM Policy... Done. Service [cloud-run-sessions] revision [cloud-run-sessions-00006-dun] has been deployed and is serving 100 percent of traffic. Service URL: https://cloud-run-sessions-dr7fcdmn3a-uc.a.run.app ``` -------------------------------- ### Install upstash-redis-dump CLI Tool Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `upstash-redis-dump` command-line interface globally using npm. This tool is required for exporting and importing Redis data, facilitating migration processes. ```bash npm install -g upstash-redis-dump ``` -------------------------------- ### TypeScript HLEN Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides a TypeScript example for the HLEN command with Upstash Redis. It shows how to set a hash and then retrieve the number of fields within that hash. ```typescript await redis.hset("key", { id: 1, username: "chronark", }); const fields = await redis.hlen("key"); console.log(fields); // 2 ``` -------------------------------- ### Get Single Random Member from Redis Set (Python) Source: https://upstash.com/docs/redis/overall/llms-txt This Python example shows how to retrieve a single random member from a Redis set using the `redis.srandmember()` command. It first adds three elements to a set named 'myset' and then asserts that the returned random member is one of the added elements. ```python redis.sadd("myset", "one", "two", "three") assert redis.srandmember("myset") in {"one", "two", "three"} ``` -------------------------------- ### Perform SINTER Operation with Python Source: https://upstash.com/docs/redis/overall/llms-txt This Python example shows how to find the intersection of two sets in Redis using the Upstash Redis client. It first adds elements to two separate sets ('set1' and 'set2') and then uses `redis.sinter()` to get the common element(s). The expected output is a set containing only 'c'. ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sinter("set1", "set2") == {"c"} ``` -------------------------------- ### Initialize Node.js Project Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Node.js project in the current directory by creating a `package.json` file for managing project metadata and dependencies. ```shell npm init ``` -------------------------------- ### Build Stateful Applications with AWS App Runner and Serverless Redis Source: https://upstash.com/docs/redis/examples Explains how to build stateful applications using AWS App Runner and Upstash Redis. This example focuses on leveraging serverless Redis for persistent data in containerized applications. ```javascript import TagFilters from "../../src/components/Filter.js" Build Stateful Applications with AWS App Runner and Serverless Redis ``` -------------------------------- ### Redis ZUNIONSTORE Command Examples (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zunionstore Demonstrates how to use the ZUNIONSTORE command in Python to perform set unions. It covers simple unions, unions with scores and aggregation, and unions with weights. Requires the 'redis' library. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunionstore(["key1", "key2"]) assert result == 5 ``` ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ```python redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` -------------------------------- ### TypeScript GETDEL Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `getdel` method with type definitions in TypeScript when interacting with Upstash Redis. It includes an example of the expected return value. ```ts type MyType = { a: number; b: string; } await redis.getdel("key"); // returns {a: 1, b: "2"} ``` -------------------------------- ### Install Node.js Dependencies for Upstash and Express Source: https://upstash.com/docs/redis/quickstarts/koyeb Installs the necessary Node.js packages: `@upstash/redis` for interacting with the Upstash Redis database and `express` for building the web application. These are essential for the demo application. ```bash npm install @upstash/redis express ``` -------------------------------- ### RPUSHX Command Usage Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the usage of the RPUSHX command in Python, demonstrating how to add elements to an existing list and the behavior when attempting to push to a non-existent key. ```APIDOC ## RPUSHX Command Usage Example (Python) ### Description Demonstrates the usage of the RPUSHX command in Python. It shows how to add elements to an existing list and the behavior when attempting to push to a non-existent key, which results in a return value of 0. ### Method `RPUSHX` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Redis client instance # Push multiple elements to an existing list redis.rpushx("mylist", "one", "two", "three") # Retrieve the list to verify redis.lrange("mylist", 0, -1) # Attempt to push to a non-existent key redis.rpushx("non-existent-list", "one") ``` ### Response #### Success Response Returns the number of elements added to the list, or 0 if the key does not exist. #### Response Example ```json 3 // For the first rpushx call 0 // For the rpushx call on a non-existent list ``` ``` -------------------------------- ### Python BITPOS Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the use of the Redis BITPOS command in Python to find the position of the first bit set to 1 or 0 in a string. Includes examples for basic usage, finding bits within a specified range, and asserting the results. Requires the `upstash-redis` Python package. ```python redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) assert redis.bitpos("mykey", 1) == 7 assert redis.bitpos("mykey", 0) == 0 # With a range assert redis.bitpos("mykey", 1, 0, 2) == 0 assert redis.bitpos("mykey", 1, 2, 3) == -1 ``` -------------------------------- ### Install Python Libraries for Web Scraping and Redis Source: https://upstash.com/docs/redis/overall/llms-txt This command installs the required Python libraries: `requests` for HTTP requests, `upstash-redis` for Redis interaction, and `python-dotenv` for loading environment variables. ```APIDOC ## Install Python Libraries for Web Scraping and Redis ### Description Installs necessary Python libraries for web scraping and Redis interaction. ### Command ```bash pip install threading requests upstash-redis python-dotenv ``` ``` -------------------------------- ### Redis SMEMBERS Command API and Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides the API documentation and a Python example for the Redis `SMEMBERS` command. This command retrieves all members from a specified Redis set. The documentation details the command's arguments (key) and response type (set of strings). The Python example shows adding members to a set and then retrieving them. ```APIDOC SMEMBERS: Description: Return all the members of a set Arguments: key: Type: str Required: true Description: The key of the set. Response: Type: set[str] Required: true Description: The members of the set. ``` ```python redis.sadd("set", "a", "b", "c"); assert redis.smembers("set") == {"a", "b", "c"} ``` -------------------------------- ### Python XADD Command with Trimming Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the XADD command in Python for adding entries to a stream, with an example of MAXLEN trimming. This ensures the stream size stays below a defined threshold. ```python redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }) ``` -------------------------------- ### Install Upstash Redis SDK Source: https://upstash.com/docs/redis/quickstarts/fastlycompute Installs the official Upstash Redis SDK for JavaScript using npm. This package provides the necessary client to interact with Upstash Redis databases from a Fastly Compute@Edge service. ```shell npm install @upstash/redis ``` -------------------------------- ### Install Drizzle ORM Package Source: https://upstash.com/docs/redis/integrations/drizzle Installs the necessary drizzle-orm package using npm. This is the first step to integrate Drizzle ORM with Upstash Redis. ```bash npm install drizzle-orm ``` -------------------------------- ### Redis GET Command Source: https://upstash.com/docs/redis/overall/llms-txt Documents the `GET` command for Upstash Redis, outlining its required arguments and the expected response format. ```APIDOC ## Redis GET Command ### Description Return the value of the specified key or `None` if the key doesn't exist. ### Method Command ### Endpoint N/A (Redis Command) ### Parameters #### Arguments - **key** (str, required) - The key to get. ### Request Example ```APIDOC Command: GET key: "mykey" ``` ### Response #### Success Response - **value** (any, required) - The response is the value stored at the key or `None` if the key doesn't exist. #### Response Example ```APIDOC # If key exists "some_value" # If key does not exist None ``` ``` -------------------------------- ### Install Upstash Redis Client for Deno Source: https://upstash.com/docs/redis/sdks/ts/getstarted Import the Upstash Redis client directly from deno.land for Deno projects. This is the primary method for Deno users. ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts"; ``` -------------------------------- ### Upstash Redis ZDIFF Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zdiff Demonstrates how to use the ZDIFF command in Upstash Redis to find the difference between two sets. This example shows the basic usage without scores. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zdiff(["key1", "key2"]) assert result == ["a", "b"] ``` -------------------------------- ### Initialize SST Source: https://upstash.com/docs/redis/overall/llms-txt Sets up SST (Serverless Stack) within the current project directory, preparing it for serverless deployment. ```APIDOC ## Initialize SST ### Description Initializes the Serverless Stack (SST) framework in the current project directory, setting up the necessary configuration for serverless deployments. ### Method Command Line Interface ### Endpoint N/A ### Parameters None ### Request Example ```bash sst init ``` ### Response SST initialization complete. Project is ready for serverless deployment configuration. ``` -------------------------------- ### Add npm Scripts for Development and Production Source: https://upstash.com/docs/redis/quickstarts/koyeb This JSON snippet shows how to update the `package.json` file to include `dev` and `start` scripts. The `dev` script enables debug logging for Express, while the `start` script runs the application normally. These scripts are essential for managing the application's lifecycle. ```json { "name": "example-koyeb-upstash", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "DEBUG=express:* node index.js", "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@upstash/redis": "^1.20.6", "express": "^4.18.2" } } ``` -------------------------------- ### LPUSH Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/lpush Demonstrates how to use the LPUSH command in Python to add elements to the beginning of a list in Upstash Redis. It verifies the operation by checking the list's length and its contents. ```python assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ``` -------------------------------- ### Connect and set key with Go Redis client Source: https://upstash.com/docs/redis/overall/llms-txt Provides a Go example for connecting to Upstash Redis and performing a SET operation. It initializes a Redis client using `redis.NewClient` with the provided URL and then sets a key-value pair. Error handling for connection and operations is included. ```go package main import ( "fmt" "github.com/redis/go-redis/v9" "context" ) func main() { ctx := context.Background() r := redis.NewClient(&redis.Options{ Addr: "", Password: "", // no password set DB: 0, // use default DB }) err := r.Set(ctx, "mykey", "Hello from Go!", 0).Err() if err != nil { panic(err) } val, err := r.Get(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println("mykey", val) } ``` -------------------------------- ### Initialize Serverless Framework Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Command to create a new Serverless Framework project using the AWS Node.js HTTP API template and name it 'counter-serverless'. This demonstrates the interactive prompts and successful project creation process. ```shell ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · counter-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · counter-serverless Your new Service "counter-serverless" is ready. Here are next steps: • Open Service Directory: cd counter-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ``` -------------------------------- ### XRANGE Command Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xrange Demonstrates how to use the XRANGE command in Upstash Redis with TypeScript. It covers fetching all entries, entries within specific IDs, and limiting the count of returned entries. Requires the Upstash Redis client library. ```typescript const result = await redis.xrange("mystream", "-", "+"); ``` ```typescript const result = await redis.xrange("mystream", "1548149259438-0", "1548149259438-5"); ``` ```typescript const result = await redis.xrange("mystream", "-", "+", 10); ``` -------------------------------- ### Initialize Nuxt.js Project Source: https://upstash.com/docs/redis/overall/llms-txt Command to create a new Nuxt.js application using the `nuxi` CLI tool. ```APIDOC ## Initialize Nuxt.js Project ### Description Creates a new Nuxt.js application. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```bash npx nuxi@latest init nuxtjs-with-redis ``` ### Response N/A ``` -------------------------------- ### Echo Command Usage Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Provides a Python example for using the `redis.echo` method. This command sends a message to the Redis server and returns the same message, which is useful for verifying connection and server responsiveness. ```Python assert redis.echo("hello world") == "hello world" ``` -------------------------------- ### Python Example for HMSET Command Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating the HMSET command in Python to set multiple fields in a Redis hash. It asserts that two fields were successfully set. ```python # Set multiple fields assert redis.hset("myhash"{ "field1": "Hello", "field2": "World" }) == 2 ``` -------------------------------- ### Upstash Redis LRANGE Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/list/lrange Demonstrates the usage of the LRANGE command in Python to fetch elements from a Redis list. It shows how to push elements into a list and then retrieve a range of elements using both positive and negative indices. ```python redis.rpush("mylist", "one", "two", "three") assert redis.lrange("mylist", 0, 1) == ["one", "two"] assert redis.lrange("mylist", 0, -1) == ["one", "two", "three"] ``` -------------------------------- ### Routes with Different Rate Limit Algorithms (JSON) Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/configurations This configuration sets distinct rate limits for different API routes. The '/api/restaurants/:id' route uses a fixed-window algorithm (10 requests/20s), while '/api/restaurants' uses a token bucket algorithm (10 tokens, 20s window, refill rate of 1). User identification is based on the 'x-author' header. It requires UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL. ```json { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "/api/restaurants/:id", "identifierSource": "header.x-author", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } }, { "methods": ["GET"], "path": "/api/restaurants", "identifierSource": "header.x-author", "limiter": { "algorithm": "tokenBucket", "tokens": 10, "window": "20s", "refillRate": 1 } } ], "prefix": "@strapi" } } } ``` -------------------------------- ### GET /websites/upstash-redis Source: https://upstash.com/docs/redis/sdks/py/commands/string/get Retrieves the value associated with a specified key from Upstash Redis. Returns None if the key is not found. ```APIDOC ## GET /websites/upstash-redis ### Description Return the value of the specified key or `None` if the key doesn't exist. ### Method GET ### Endpoint /websites/upstash-redis ### Parameters #### Query Parameters - **key** (str) - Required - The key to get. ### Request Example ```py # Example theme={"system"} redis.set("key", "value") assert redis.get("key") == "value" ``` ### Response #### Success Response (200) - **value** (any) - The value stored at the key or `None` if the key doesn't exist. #### Response Example ```json { "value": "value" } ``` ``` -------------------------------- ### Initialize Koyeb App with Upstash Redis via CLI Source: https://upstash.com/docs/redis/quickstarts/koyeb Initializes a new Koyeb application from a GitHub repository, configuring environment variables for Upstash Redis and port mappings. Requires replacing placeholders with actual GitHub and Upstash credentials. ```bash koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ``` -------------------------------- ### Install Dependencies for FastAPI and Upstash Redis Source: https://upstash.com/docs/redis/tutorials/python_fastapi_caching Installs the necessary Python packages for building a FastAPI application with Upstash Redis caching. This includes the FastAPI framework, the Upstash Redis client, and a Uvicorn ASGI server. ```shell pip install fastapi upstash-redis uvicorn[standard] ``` -------------------------------- ### Redis SUNIONSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt This entry represents the SUNIONSTORE command for Redis. No specific code example or description was provided in the source. ```redis SUNIONSTORE ``` -------------------------------- ### Install Celery with Redis Support Source: https://upstash.com/docs/redis/integrations/celery Installs the Celery library with the necessary Redis integration for use as a message broker and result backend. This command uses pip to manage Python packages. ```bash pip install "celery[redis]" ``` -------------------------------- ### Python Example for ZPOPMAX Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the ZPOPMAX command in Python. It demonstrates adding elements to a sorted set and then asserting the retrieval of the highest-scoring member. ```APIDOC ## Python Example for ZPOPMAX ### Description Illustrates how to use the ZPOPMAX command in Python. It demonstrates adding elements to a sorted set and then asserting the correct retrieval of the highest-scoring member. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```py redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmax("myset") == [("c", 3)] ``` ### Response #### Success Response Returns the member with the highest score and its score. If the set is empty, returns an empty list. #### Response Example ```json [["c", 3]] ``` ``` -------------------------------- ### Build a Leaderboard API at Edge Using Cloudflare Workers and Redis Source: https://upstash.com/docs/redis/examples Details the creation of an edge leaderboard API using Cloudflare Workers and Upstash Redis. This example showcases real-time data handling at the network edge. ```javascript import TagFilters from "../../src/components/Filter.js" Build a Leaderboard API at Edge Using Cloudflare Workers and Redis ``` -------------------------------- ### Python RENAMENX Example Source: https://upstash.com/docs/redis/sdks/py/commands/generic/renamenx Demonstrates the usage of the RENAMENX command in Python. It shows how to rename a key if the destination key does not exist, handling cases where the rename fails due to the destination key already existing. It also verifies the state of keys after successful and failed rename operations. ```python redis.set("key1", "Hello") redis.set("key2", "World") # Rename failed because "key2" already exists. assert redis.renamenx("key1", "key2") == False assert redis.renamenx("key1", "key3") == True assert redis.get("key1") is None assert redis.get("key2") == "World" assert redis.get("key3") == "Hello" ``` -------------------------------- ### Install Upstash Redis with Next.js Pages Router Source: https://upstash.com/docs/redis/quickstarts/nextjs-pages-router Installs the necessary packages for a Next.js application using the Pages Router and the Upstash Redis client. ```shell npx create-next-app@latest cd my-app npm install @upstash/redis ``` -------------------------------- ### Job Processing and Event Queue with Serverless Redis Source: https://upstash.com/docs/redis/examples Demonstrates implementing job processing and event queues using Upstash Redis with AWS Lambda and Node.js. This example focuses on asynchronous task management. ```javascript import TagFilters from "../../src/components/Filter.js" Job Processing and Event Queue with Serverless Redis ``` -------------------------------- ### Building React Native Apps Backed by AWS Lambda and Serverless Redis Source: https://upstash.com/docs/redis/examples Details how to build React Native mobile applications powered by AWS Lambda and Upstash Redis. This example focuses on creating serverless backends for mobile apps. ```javascript import TagFilters from "../../src/components/Filter.js" Building React Native Apps Backed by AWS Lambda and Serverless Redis ``` -------------------------------- ### Create Next.js App and Initialize SST Source: https://upstash.com/docs/redis/quickstarts/ion Commands to create a new Next.js application and initialize the Serverless Stack (SST) framework within the project. SST simplifies the deployment of serverless applications on AWS. ```shell npx create-next-app@latest cd my-app sst init ``` -------------------------------- ### Install FastAPI and Upstash Rate Limiting Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt This command installs the necessary Python packages for building a FastAPI application with Upstash Redis for rate limiting, including the ASGI server Uvicorn. ```APIDOC ## Install FastAPI and Upstash Rate Limiting Dependencies ### Description Installs Python packages required for a FastAPI application with Upstash Redis rate limiting. ### Command ```shell pip install fastapi upstash-redis upstash-ratelimit uvicorn[standard] ``` ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Changes the current working directory to a specified project folder, such as 'ratelimit-serverless'. This is a common prerequisite for project setup. ```bash cd ratelimit-serverless ``` -------------------------------- ### Install and Initialize Cloudflare Workers Project Source: https://upstash.com/docs/redis/overall/llms-txt This series of shell commands installs the Wrangler CLI globally, logs the user into their Cloudflare account, and generates a new 'edge-leaderboard' Cloudflare Workers project. ```shell npm install -g @cloudflare/wrangler ``` ```shell wrangler login ``` ```shell wrangler generate edge-leaderboard ``` -------------------------------- ### Install Upstash Ratelimit Strapi Plugin Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/getting-started Install the Upstash Ratelimit Strapi plugin using either npm or yarn. This package adds rate-limiting capabilities to your Strapi application, protecting your APIs from excessive requests. ```bash npm install --save @upstash/strapi-plugin-upstash-ratelimit ``` ```bash yarn add @upstash/strapi-plugin-upstash-ratelimit ``` -------------------------------- ### Install Python Dependencies for Upstash Redis Session Management Source: https://upstash.com/docs/redis/tutorials/python_session Installs necessary Python libraries including FastAPI, Upstash Redis client, Uvicorn for running the server, and python-dotenv for managing environment variables. ```bash pip install fastapi upstash-redis uvicorn python-dotenv ``` -------------------------------- ### Install Upstash Redis SDK Source: https://upstash.com/docs/redis/overall/llms-txt This command installs the `@upstash/redis` SDK, which is a crucial dependency for interacting with your Upstash Redis database from within your Cloudflare Worker application. It enables programmatic access to Redis functionalities. ```APIDOC ## Install Upstash Redis SDK ### Description Installs the `@upstash/redis` SDK for Node.js environments. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example ```bash npm install @upstash/redis ``` ### Response None ``` -------------------------------- ### RPUSHX Example with Existing List (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/rpushx Demonstrates using the RPUSHX command to push elements to an existing list in Upstash Redis. It first pushes elements 'a', 'b', 'c' to 'key' using lpush, then pushes 'd' using rpushx, and logs the final length. ```typescript await redis.lpush("key", "a", "b", "c"); const length = await redis.rpushx("key", "d"); console.log(length); // 4 ``` -------------------------------- ### Initialize AWS SAM Project Source: https://upstash.com/docs/redis/overall/llms-txt Command to initialize a new AWS Serverless Application Model (SAM) project. This command typically prompts the user for template selection, runtime, and project name, setting up the foundational structure for a serverless application. ```shell sam init ``` -------------------------------- ### LPUSH Command Example (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/lpush Demonstrates how to use the LPUSH command to add elements to the beginning of a list in Upstash Redis. It shows pushing multiple elements at once and then a single element, logging the resulting list length after each operation. This function requires a Redis client instance. ```typescript const length1 = await redis.lpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.lpush("key", "d"); console.log(length2); // 4 ``` -------------------------------- ### Node.js Project Scripts for npm Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions This JSON snippet defines the `scripts` section for a `package.json` file in a Node.js project. It includes a `start` script that executes the `index.js` file using `node`, which is commonly used to run the application. The `test` script is a placeholder. ```json { "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } } ``` -------------------------------- ### AWS Lambda Rate Limiting with Serverless Redis Source: https://upstash.com/docs/redis/examples Explains how to implement rate limiting for AWS Lambda functions using Upstash Redis. This example focuses on API security and resource management. ```javascript import TagFilters from "../../src/components/Filter.js" AWS Lambda Rate Limiting with Serverless Redis ``` -------------------------------- ### SETRANGE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the SETRANGE command in Redis with a Python client, including setting an initial value, applying SETRANGE, and verifying the result. ```APIDOC ## SETRANGE Command Example (Python) ### Description Demonstrates the SETRANGE command in Python. It shows setting an initial string value, then overwriting a portion of it using SETRANGE, and finally verifying the updated value. ### Method `SETRANGE` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Redis client instance # Set an initial value for the key redis.set("key", "Hello World") # Use SETRANGE to overwrite starting from index 6 redis.setrange("key", 6, "Redis") # Get the final value of the key redis.get("key") ``` ### Response #### Success Response Returns the new length of the string after modification. #### Response Example ```json 11 // The new length of the string "Hello Redis" ``` ``` -------------------------------- ### Scoreboard with Upstash Redis (React Example) Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates building a React scoreboard that uses Upstash Redis to store and retrieve scores. ```APIDOC ## React Scoreboard with Upstash Redis ### Description Provides example functions for updating and retrieving scores in a scoreboard stored in Upstash Redis. ### Method POST (Implied by `redis.zadd` and `redis.zrevrange`) ### Endpoint `/redis/commands ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for `updateScore`) ```json { "command": "zadd", "key": "scoreboard", "members": [ {"score": , "value": ""} ] } ``` #### Request Body (for `getTopScores`) ```json { "command": "zrevrange", "key": "scoreboard", "start": 0, "stop": "", "options": {"withScores": true} } ``` ### Request Example ```javascript // Example score update and retrieval async function updateScore(playerName, score) { await redis.zadd('scoreboard', { score: score, value: playerName }); } async function getTopScores(count) { return await redis.zrevrange('scoreboard', 0, count - 1, { withScores: true }); } ``` ### Response #### Success Response (200) for `getTopScores` - **Array**: An array of objects, each containing player name and score. #### Response Example for `getTopScores` ```json [ {"value": "PlayerA", "score": 100}, {"value": "PlayerB", "score": 95} ] ``` ``` -------------------------------- ### TypeScript Example for HSETNX Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the HSETNX command in TypeScript with an async Redis client. ```APIDOC ## HSETNX Command in TypeScript ### Description Set the value of a hash field, only if the field does not exist. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the hash. - **field** (string) - Required - The field to set. - **value** (any) - Required - The value to set. ### Request Example ```ts await redis.hsetnx("key", "id", 1) ``` ### Response #### Success Response (200) - **type** (integer) - Returns 1 if the field is new and was set, 0 if the field already existed. #### Response Example ```json 1 ``` ``` -------------------------------- ### ZDIFFSTORE Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zdiffstore Demonstrates how to use the ZDIFFSTORE command in Python to find the difference between two sorted sets and store the result in a new key. It first adds elements to two sets, then uses zdiffstore to compute the difference, and asserts the size of the resulting set. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) # a and b assert redis.zdiffstore("dest", ["key1", "key2"]) == 2 ``` -------------------------------- ### SMOVE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of the SMOVE command in Python using a Redis client. This example shows how to add members to sets, move a member from a source set to a destination set, and then verify the state of both sets after the operation. ```APIDOC ## SMOVE Command Example (Python) ### Description Demonstrates the SMOVE command in Python. It shows adding members to source and destination sets, moving a member from source to destination, and verifying the sets' contents. ### Method `SMOVE` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Redis client instance # Add members to the source set redis.sadd("src", "one", "two", "three") # Add a member to the destination set redis.sadd("dest", "four") # Move a member from 'src' to 'dest' redis.smove("src", "dest", "three") # Verify the contents of the source set redis.smembers("src") # Verify the contents of the destination set redis.smembers("dest") ``` ### Response #### Success Response Returns `True` if the member was moved. Returns `False` if the member was not a member of the source set. #### Response Example ```json true // If 'three' was successfully moved ``` ``` -------------------------------- ### RPUSHX Example without Existing List (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/rpushx Illustrates the behavior of the RPUSHX command when the target list does not exist. It attempts to push 'a' to a non-existent 'key' and logs the returned length, which will be 0. ```typescript const length = await redis.rpushx("key", "a"); console.log(length); // 0 ``` -------------------------------- ### Install Node.js Dependencies for Redis and Histogram Source: https://upstash.com/docs/redis/overall/llms-txt Commands to install the necessary Node.js packages: `ioredis` for interacting with the Redis database and `hdr-histogram-js` for building and manipulating histogram data. ```APIDOC ## Install Node.js Dependencies ### Description Installs the `ioredis` and `hdr-histogram-js` Node.js packages, which are essential for interacting with Upstash Redis and handling histogram data, respectively. ### Method Package Installation ### Endpoint N/A ### Parameters None ### Request Example ```bash npm install ioredis npm install hdr-histogram-js ``` ### Response Package installation successful. ``` -------------------------------- ### LINSERT Command TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the LINSERT command with an Upstash Redis client in TypeScript. The example first populates a list using RPUSH and then demonstrates inserting a new element 'x' before 'b' using LINSERT. ```APIDOC ## LINSERT Command TypeScript Example ### Description This example demonstrates using the `LINSERT` command with the Upstash Redis client in TypeScript. It shows how to add an element to a list before a specified existing element. ### Method Not Applicable (SDK method) ### Endpoint Not Applicable (SDK method) ### Parameters Not Applicable (SDK method) ### Request Example ```ts await redis.rpush("key", "a", "b", "c"); await redis.linsert("key", "before", "b", "x"); ``` ### Response Not Applicable (SDK method) ``` -------------------------------- ### Python LSET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt A Python code example demonstrating how to use the LSET command with a Redis client. It illustrates pushing elements to a list, setting a value at a valid index, and verifying the list content, as well as handling attempts to set values at out-of-range indices. ```APIDOC ## Python LSET Command Example ### Description Demonstrates the usage of the LSET command in Python to update an element at a specific index in a Redis list. ### Method `redis.lset(key, index, value)` ### Example ```python redis.rpush("mylist", "one", "two", "three") # Update element at index 1 assert redis.lset("mylist", 1, "Hello") == True assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] # Attempt to update element at out-of-range index assert redis.lset("mylist", 5, "Hello") == False assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] ``` ``` -------------------------------- ### Python Example for ZCARD Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZCARD command with the Upstash Redis client in Python. This example first adds elements to a sorted set and then asserts that ZCARD correctly returns the count of elements. ```APIDOC ## ZCARD Command in Python ### Description Get the number of elements in a sorted set. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the sorted set. ### Request Example ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) ``` ### Response #### Success Response (200) - **type** (integer) - The number of elements in the sorted set. #### Response Example ```python 3 ``` ``` -------------------------------- ### Python BITOP Example for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the `BITOP` command in Python for performing bitwise operations on Redis keys. It includes setting bits, performing an AND operation, and asserting the results. ```python # key1 = 00000001 # key2 = 00000010 redis.setbit("key1", 0, 1) redis.setbit("key2", 0, 0) redis.setbit("key2", 1, 1) assert redis.bitop("AND", "dest", "key1", "key2") == 1 # result = 00000000 assert redis.getbit("dest", 0) == 0 assert redis.getbit("dest", 1) == 0 ``` -------------------------------- ### blockUntilReady() Behavior Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/costs Explains that the `blockUntilReady()` method functions identically to the `limit()` method in terms of command execution. ```APIDOC ## GET/POST /websites/upstash-redis/blockUntilReady ### Description This method operates identically to the `limit()` method regarding command execution and Redis interactions. ### Method GET/POST ### Endpoint /websites/upstash-redis/blockUntilReady ### Parameters [Parameters are the same as the `limit()` method, refer to its documentation.] ### Response #### Success Response (200) [Response structure is the same as the `limit()` method.] #### Response Example [Response example is the same as the `limit()` method.] ``` -------------------------------- ### Python ZADD Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Shows various Python examples for the ZADD command, including adding multiple elements, conditional additions using 'nx', conditional updates using 'xx', and score updates with 'gt'. ```python # Add three elements assert redis.zadd("myset", { "one": 1, "two": 2, "three": 3 }) == 3 ``` ```python # No element is added since "one" and "two" already exist assert redis.zadd("myset", { "one": 1, "two": 2 }, nx=True) == 0 ``` ```python # New element is not added since it does not exist assert redis.zadd("myset", { "new-element": 1 }, xx=True) == 0 ``` ```python # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 ``` ```python # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 ``` -------------------------------- ### Deploy Cloudflare Worker Source: https://upstash.com/docs/redis/tutorials/cloudflare_websockets_redis Commands to install dependencies and deploy the Cloudflare Worker. This involves navigating to the worker directory, installing necessary packages using pnpm, and then deploying the worker using npm. ```bash cd worker pnpm install npm run deploy ``` -------------------------------- ### Python ZUNION Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates various usages of the `redis.zunion` command in Python for combining sorted sets. Examples include simple union, union with scores, and weighted union operations. Requires Redis client and pre-populated sorted sets. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunion(["key1", "key2"]) assert result == ["a", "b", "c", "d", "e"] ``` ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ```python redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` -------------------------------- ### Python GETDEL Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the `GETDEL` command in Python, which retrieves the value associated with a key and then deletes the key from Redis. The example verifies the retrieved value and confirms the key's subsequent deletion. ```python redis.set("key", "value") assert redis.getdel("key") == "value" assert redis.get("key") == None ``` -------------------------------- ### Python HGETALL Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using `hset` to populate a Redis hash and then `hgetall` to retrieve all fields and values from that hash using a Python Redis client. Includes an assertion for verification. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hgetall("myhash") == {"field1": "Hello", "field2": "World"} ``` -------------------------------- ### Redis GET Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Documents the `GET` command for Upstash Redis, outlining its required arguments (key) and the expected response format (value or None if the key doesn't exist). ```apidoc Command: GET Description: Return the value of the specified key or `None` if the key doesn't exist. Arguments: key (str, required): The key to get. Response: (any, required): The response is the value stored at the key or `None` if the key doesn't exist. ``` -------------------------------- ### Serverless Python API with Redis Example Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder example for creating a serverless Python API using Upstash Redis, often utilized with AWS Lambda. This demonstrates a basic Python script structure. ```Python print("This is a placeholder for Python code.") ``` -------------------------------- ### Initialize Upstash Redis Client from Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize the Upstash Redis client by automatically loading configuration from environment variables and performs a `get` operation. ```APIDOC ## Initialize Upstash Redis Client from Environment Variables (TypeScript) ### Description This TypeScript example shows how to initialize the Upstash Redis client by automatically loading configuration from environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`). It then performs an asynchronous `get` operation to retrieve data from Redis, logging the result or any encountered errors. ### Method TypeScript Code ### Endpoint N/A ### Parameters #### Environment Variables (Required) - **UPSTASH_REDIS_REST_URL** (string) - The URL of the Upstash Redis REST endpoint. - **UPSTASH_REDIS_REST_TOKEN** (string) - The token for authenticating with Upstash Redis. ### Request Example ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv()(); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ### Response #### Success Response - **data** (any) - The value retrieved from Redis, or `null` if the key does not exist. #### Response Example ```json "some_value" ``` #### Error Response - **error** (object) - An error object if the operation fails. ``` -------------------------------- ### ZADD and ZLEXCOUNT Example in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zlexcount This example demonstrates how to add elements to a sorted set using ZADD and then count elements within a lexicographical range using ZLEXCOUNT in TypeScript. It requires the Upstash Redis client library. ```typescript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zlexcount("key", "two", "+"); console.log(elements); // 1 ``` -------------------------------- ### Perform BITOP AND Operation in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/bitmap/bitop Executes the BITOP command with the AND operation on source keys and stores the result in a destination key. This example assumes a Redis client instance named 'redis' is available. ```typescript await redis.bitop("AND", "destKey", "sourceKey1", "sourceKey2"); ``` -------------------------------- ### TypeScript JSON.GET Usage Examples Source: https://upstash.com/docs/redis/overall/llms-txt Examples demonstrating `redis.json.get` in TypeScript for retrieving values from JSON documents. Covers basic path-based retrieval and advanced usage with formatting options like indentation, newlines, and spaces. ```typescript const value = await redis.json.get("key", "$.path.to.somewhere"); ``` ```typescript const value = await redis.json.get("key", { indent: " ", newline: "\n", space: " " }, "$.path.to.somewhere"); ``` -------------------------------- ### Example Redis Commands for Pipelining (Redis) Source: https://upstash.com/docs/redis/overall/llms-txt A set of standard Redis commands (`SET`, `SETEX`, `INCR`, `ZADD`) formatted for submission via the Upstash pipelining API. Pipelining allows for sending multiple commands at once to reduce latency. ```redis SET key1 valuex SETEX key2 13 valuez INCR key1 ZADD myset 11 item1 22 item2 ``` -------------------------------- ### Run FastAPI Application using Uvicorn Source: https://upstash.com/docs/redis/overall/llms-txt Command to start a FastAPI application using Uvicorn, an ASGI server, with live reloading enabled for development. ```APIDOC ## Uvicorn Command ### Description Starts a FastAPI application using Uvicorn with live reloading. ### Method N/A (Shell Command) ### Endpoint N/A (Shell Command) ### Parameters N/A (Shell Command) ### Request Example ```shell uvicorn main:app --reload ``` ### Response N/A (Shell Command) ``` -------------------------------- ### Navigate into the newly created Phoenix project directory Source: https://upstash.com/docs/redis/overall/llms-txt After creating the Phoenix application, use this command to change the current working directory to the newly generated project folder, `redix_demo`. This is a necessary step before proceeding with further configurations and dependency installations within the project. ```APIDOC ## Navigate into the newly created Phoenix project directory ### Description Changes the current working directory to the specified project folder. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example ```Shell cd redix_demo ``` ### Response None ``` -------------------------------- ### TypeScript JSON.STRAPPEND Example Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the JSON.STRAPPEND command with the Upstash Redis client in TypeScript, appending a string value to a specified path within a JSON key. ```APIDOC ## TypeScript JSON.STRAPPEND Example ### Description Demonstrates appending a string value to a specified path within a JSON key using `JSON.STRAPPEND` in TypeScript. ### Method `redis.json.strappend(key, path, value)` ### Example ```ts await redis.json.strappend("key", "$.path.to.str", "abc"); ``` ``` -------------------------------- ### ZPOPMAX Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zpopmax Demonstrates how to use the ZPOPMAX command to remove and retrieve members with the highest scores from a Redis sorted set. It requires the 'redis' library and assumes a Redis client instance is available. ```python redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmax("myset") == [("c", 3)] ``` -------------------------------- ### ZINTERSTORE with Aggregation Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `aggregate` option with `redis.zinterstore` to specify how scores are combined when multiple input sets contain the same member. This example uses 'sum' aggregation. ```APIDOC ## ZINTERSTORE with Aggregation ### Description Computes the intersection of multiple sorted sets and stores the result in a new sorted set, with an option to aggregate scores. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Arguments - **destination** (string) - The key of the destination sorted set. - **numkeys** (number) - The number of input sorted sets. - **keys** (string[]) - An array of keys for the input sorted sets. - **options** (object) - Optional. Configuration for aggregation. - **aggregate** ("sum" | "min" | "max") - Specifies how to aggregate scores of elements common to multiple input sets. ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zinterstore( "destination", 2, ["key1", "key2"], { aggregate: "sum" }, ); console.log(res) // 1 ``` ### Response #### Success Response (200) - **result** (number) - The number of elements in the resulting sorted set. #### Response Example ```json 1 ``` ``` -------------------------------- ### Publish Message with Upstash QStash Client Source: https://upstash.com/docs/redis/howto/vercelintegration Shows how to use the Upstash QStash client to publish a JSON message to a specified URL. Requires the '@upstash/qstash' package and QSTASH_TOKEN environment variable. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: process.env.QSTASH_TOKEN, }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); ``` -------------------------------- ### Install Node.js Dependencies for Redis and Histogram Source: https://upstash.com/docs/redis/overall/llms-txt Provides shell commands to install necessary Node.js packages, specifically 'ioredis' for Redis client functionality and 'hdr-histogram-js' for histogram data manipulation. ```text npm install ioredis npm install hdr-histogram-js ``` -------------------------------- ### TypeScript BITCOUNT Examples for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of the `redis.bitcount` method in TypeScript. Examples show counting bits in a whole key and within a specified byte range. ```typescript const bits = await redis.bitcount(key); ``` ```typescript const bits = await redis.bitcount(key, 5, 10); ``` -------------------------------- ### Build and Deploy AWS SAM Application Source: https://upstash.com/docs/redis/tutorials/using_aws_sam These shell commands are used to build the serverless application artifacts and then deploy the application to AWS. The 'sam deploy --guided' command initiates an interactive deployment process where environment variables, including Upstash Redis credentials, are prompted. ```shell sam build sam deploy --guided ``` -------------------------------- ### TypeScript Example for LPUSH Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the LPUSH command with the Upstash Redis client in TypeScript, showing multiple pushes and the resulting list length. ```APIDOC ## LPUSH Command in TypeScript ### Description Insert one or more values at the head of a list. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the list. - **value** (*string) - Required - One or more values to insert. ### Request Example ```typescript const length1 = await redis.lpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.lpush("key", "d"); console.log(length2); // 4 ``` ### Response #### Success Response (200) - **type** (integer) - The length of the list after the push operation. #### Response Example ```json 4 ``` ``` -------------------------------- ### Get Latency Histogram with cURL Source: https://upstash.com/docs/redis/tutorials/histogram Retrieves the latency histogram for a specified test name via a GET request to the API endpoint. This allows for analysis of performance metrics. ```shell curl https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get?name=perf-test-1 ``` -------------------------------- ### Install Upstash Redis SDK for Node.js Source: https://upstash.com/docs/redis/tutorials/cloudflare_workers_with_redis Installs the official Upstash Redis JavaScript SDK as a dependency for the Cloudflare Worker project. This allows the worker to interact with the Upstash Redis database. ```shell cd greetings-cloudflare npm install @upstash/redis ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt This snippet demonstrates how to create a new directory for the project and navigate into it using standard shell commands. ```APIDOC ## Create Project Directory ### Description This snippet demonstrates how to create a new directory for the project and navigate into it using standard shell commands. This is the initial step for setting up the project structure. ### Method Shell commands ### Endpoint N/A ### Parameters N/A ### Request Example ```bash mkdir cloud-run-sessions cd cloud-run-sessions ``` ### Response N/A ``` -------------------------------- ### Python Example for MSET Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt This Python snippet demonstrates how to use the `MSET` command with the Upstash Redis client to efficiently set multiple key-value pairs in a single operation. ```python redis.mset({ "key1": "value1", "key2": "value2" }) ``` -------------------------------- ### ZDIFFSTORE Command Example (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zdiffstore Demonstrates how to use the ZDIFFSTORE command in Upstash Redis to compute the difference between sets and store the result in a new key. This function requires the 'redis' client instance and takes the destination key, the number of keys to compare, and the keys themselves as arguments. ```typescript const values = await redis.zdiffstore("destination", 2, "key1", "key2"); ``` -------------------------------- ### Upstash Redis ZRANGE Command Examples (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zrange Demonstrates how to use the ZRANGE command in Upstash Redis with Python. It covers basic range retrieval, reversing the order, sorting by score, and including scores in the output. Requires the 'redis' library. ```python import redis redis_client = redis.Redis(host='YOUR_REDIS_HOST', port=YOUR_REDIS_PORT, password='YOUR_REDIS_PASSWORD') # Example 1: Basic ZRANGE redis_client.zadd("myset", {"a": 1, "b": 2, "c": 3}) print(f"Basic ZRANGE: {redis_client.zrange('myset', 0, 1)}") # Example 2: ZRANGE with reverse order print(f"Reverse ZRANGE: {redis_client.zrange('myset', 0, 1, rev=True)}") # Example 3: ZRANGE sorted by score print(f"Sorted ZRANGE: {redis_client.zrange('myset', 0, 1, sortby='BYSCORE')}") # Example 4: ZRANGE with scores print(f"Zrange with scores: {redis_client.zrange('myset', 0, 1, withscores=True)}") ``` -------------------------------- ### HSETNX Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hsetnx This Python code snippet demonstrates the usage of the HSETNX command with Upstash Redis. It shows how to set a field if it doesn't exist and verifies the behavior when the field already exists. This function requires a Redis client instance. ```python assert redis.hsetnx("myhash", "field1", "Hello") == True assert redis.hsetnx("myhash", "field1", "World") == False ``` -------------------------------- ### Subscribe to Channels by Patterns with PSUBSCRIBE (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/pubsub/psubscribe This example demonstrates how to subscribe to Redis channels using patterns with the PSUBSCRIBE command in TypeScript. It shows how to handle incoming messages and filters them based on the provided patterns. Dependencies include the Upstash Redis client library. ```typescript const subscription = redis.psubscribe(["user:*"]); const messages = []; subscription.on("pmessage", (data) => { messages.push(data.message); }); await redis.publish("user:123", "user:123 message"); // receives await redis.publish("user:456", "user:456 message"); // receives await redis.publish("other:789", "other:789 message"); // doesn't receive console.log(messages[0]) // user:123 message console.log(messages[1]) // user:456 message console.log(messages[2]) // undefined ``` -------------------------------- ### Upstash Redis JSON.RESP Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt A Python example for calling the `JSON.RESP` command to retrieve a value from a JSON entry stored in Redis, specifying the key and the JSON path. ```Python resp = redis.json.resp("key", "$.path") ``` -------------------------------- ### Create Java Maven Serverless Project Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Creates a new serverless project using the aws-java-maven template. This command initializes the project structure and build configuration. ```shell serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ``` -------------------------------- ### Perform BITOP AND operation in Python Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitop Demonstrates how to use the BITOP command with the AND operation in Python. It sets initial bit values in 'key1' and 'key2', performs the AND operation, and stores the result in 'dest'. The response indicates the size of the resulting string. ```python redis.setbit("key1", 0, 1) redis.setbit("key2", 0, 0) redis.setbit("key2", 1, 1) assert redis.bitop("AND", "dest", "key1", "key2") == 1 # result = 00000000 assert redis.getbit("dest", 0) == 0 assert redis.getbit("dest", 1) == 0 ``` -------------------------------- ### Shell: Create Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt A standard shell command to create a new directory for a project and then change the current working directory into the newly created one. This is a foundational step for project setup. ```bash mkdir cloud-run-sessions cd cloud-run-sessions ``` -------------------------------- ### TypeScript Example for SDIFFSTORE Usage Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the SDIFFSTORE command with Upstash Redis in TypeScript, showing how to add members to sets, calculate the difference, and store the result. ```APIDOC ## SDIFFSTORE Command (TypeScript) ### Description Calculates the difference between sets and stores the result in a destination key. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```ts await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sdiff("dest", "set1", "set2"); console.log(diff); // ["a", "b"] ``` ### Response N/A (Code Example) ``` -------------------------------- ### Install Node.js Dependencies for Express Session (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt This bash command installs necessary Node.js packages for integrating Redis-backed session management in an Express application. It includes 'express', 'redis', 'connect-redis', and 'express-session'. ```bash npm install express redis connect-redis express-session ``` -------------------------------- ### Run Supabase Locally and Serve Function Source: https://upstash.com/docs/redis/quickstarts/supabase Starts the Supabase local development environment and serves the 'upstash-redis-counter' function. The `--no-verify-jwt` flag bypasses JWT verification, and `--env-file` specifies the environment configuration. ```bash supabase start supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### HTTL Usage Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the HTTL command with the `upstash-redis` client in TypeScript. This example shows setting a hash field, applying an expiration, and then retrieving its remaining TTL. ```APIDOC ## HTTL Command in TypeScript ### Description Get the time to live for a specific field in a hash. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the hash. - **field** (string) - Required - The field within the hash. ### Request Example ```typescript await redis.hset("my-key", "my-field", "my-value"); await redis.hexpire("my-key", "my-field", 10); const ttl = await redis.httl("my-key", "my-field"); console.log(ttl); // e.g., [9] ``` ### Response #### Success Response (200) - **type** (integer) - The remaining time to live of the field in seconds. Returns -1 if the field exists but has no associated expire, and -2 if the field does not exist. #### Response Example ```json 9 ``` ``` -------------------------------- ### Add HTTPoison Dependency (Mix) Source: https://upstash.com/docs/redis/quickstarts/elixir Instructions to add the HTTPoison library as a dependency in your Elixir project's mix.exs file and fetch it. ```bash mix deps.get ``` -------------------------------- ### Get Value from Upstash Redis (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/string/get Retrieves the value associated with a specified key from Upstash Redis. If the key does not exist, it returns None. This function requires a Redis client instance. ```python redis.set("key", "value") assert redis.get("key") == "value" ``` -------------------------------- ### TypeScript Example for LTRIM Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `lpush` and `ltrim` commands with Upstash Redis in TypeScript to initialize a list and then trim it to a specific range. ```APIDOC ## Trim List (LTRIM) ### Description Initializes a list with several elements and then trims it to a specified range using LTRIM. ### Method POST ### Endpoint /api/redis/list/ltrim ### Parameters #### Request Body - **key** (string) - Required - The key of the list. - **start** (integer) - Required - The start index of the range to keep (inclusive). - **end** (integer) - Required - The end index of the range to keep (inclusive). ### Request Example ```json { "key": "key", "start": 1, "end": 2 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the operation was successful. #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### HSETNX Command Example (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/hash/hsetnx Demonstrates how to use the HSETNX command in TypeScript to set a field in a Redis hash only if the field does not already exist. This function requires a Redis client instance. ```typescript await redis.hsetnx("key", "id", 1) ``` -------------------------------- ### GETBIT Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `getbit` method with a Redis client in Python to retrieve a single bit at a specific offset from a given key. ```APIDOC ## GETBIT Command (Python) ### Description Retrieves a single bit at a specific offset from a given key. ### Method Client Method Call ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python bit = redis.getbit(key, 4) ``` ### Response #### Success Response (200) - **bit** (integer) - The bit value (0 or 1) at the specified offset. ``` -------------------------------- ### Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions This Dockerfile is a basic configuration for deploying a Node.js application. It uses the official Node.js 12 slim image as a base, sets the working directory to `/usr/src/app`, and copies the application dependency manifests (`package.json` and `package-lock.json`) into the container. This is the initial setup for building a container image. ```dockerfile # Use the official lightweight Node.js 12 image. # https://hub.docker.com/_/node FROM node:12-slim # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. ``` -------------------------------- ### MSETNX Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt API documentation for the MSETNX command, detailing its purpose, arguments, and response format. MSETNX allows setting multiple keys simultaneously only if none of them already exist. ```APIDOC ## MSETNX Command ### Description Set multiple keys in one go unless they exist already. Counts as a single command for billing. ### Method POST ### Endpoint /redis/v1/msetnx ### Parameters #### Query Parameters - **key** (string) - Required - The key to set. - **value** (any) - Required - The value to set for the key. #### Request Body - **key1** (string) - Required - The first key to set. - **value1** (any) - Required - The value for the first key. - **key2** (string) - Required - The second key to set. - **value2** (any) - Required - The value for the second key. ### Request Example ```json { "key1": "value1", "key2": "value2" } ``` ### Response #### Success Response (200) - **result** (boolean) - True if all keys were set, False if at least one key was not set. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Python ZRANDMEMBER Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrative Python code demonstrating how to use the ZRANDMEMBER command with the Upstash Redis client, showing examples for retrieving a single random member and multiple random members from a sorted set. ```APIDOC ## Python ZRANDMEMBER Command Example ### Description Demonstrates the usage of the `ZRANDMEMBER` command in Python for retrieving random members from a sorted set. ### Method `redis.zrandmember(key, count=None)` ### Example ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) # Get a single random member # Example output: "one" redis.zrandmember("myset") # Get multiple random members # Example output: ["one", "three"] redis.zrandmember("myset", 2) ``` ``` -------------------------------- ### Redis GET Command Source: https://upstash.com/docs/redis/overall/llms-txt This snippet represents the basic Redis GET command, used to retrieve the value associated with a specific key in the Redis data store. ```redis GET ``` -------------------------------- ### Redis ZINTER Command with Weights (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zinter Shows how to apply weights to sets when calculating their intersection using the ZINTER command. This example uses weights and SUM aggregation to compute a weighted intersection. ```python redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` -------------------------------- ### Sorted Set Operations Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates common sorted set operations in Python, specifically adding members with `redis.zadd` and then verifying the count of elements using `redis.zlexcount`. This example is related to sorted set management. ```APIDOC ## Sorted Set Operations Example (Python) ### Description Adds members to a sorted set and then counts the number of elements within a lexicographical range. ### Method APICALL ### Endpoint /redis/zadd & /redis/zlexcount ### Parameters #### Query Parameters (zadd) - **key** (str) - Required - The key of the sorted set. - **members** (Dict[str, Union[int, float]]) - Required - A dictionary of members and their scores. #### Query Parameters (zlexcount) - **key** (str) - Required - The key of the sorted set. - **min** (str) - Required - The minimum lexicographical value. - **max** (str) - Required - The maximum lexicographical value. ### Request Example (zadd) ```json { "key": "myset", "members": {"a": 1, "b": 2, "c": 3} } ``` ### Response (zlexcount) #### Success Response (200) - **Count** (int) - The number of elements in the specified lexicographical range. #### Response Example ```json 3 ``` ``` -------------------------------- ### Install Dependencies for FastAPI Rate Limiting Source: https://upstash.com/docs/redis/tutorials/python_rate_limiting Installs the necessary Python packages for building a FastAPI application with Upstash Redis rate limiting. This includes the FastAPI framework, the Upstash Redis client, and the Upstash rate limiting package, along with an ASGI server. ```shell pip install fastapi upstash-redis upstash-ratelimit uvicorn[standard] ``` -------------------------------- ### TypeScript Example for EVALSHA Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the EVALSHA command in TypeScript with the redis client, showing a basic execution and logging the result. ```APIDOC ## EVALSHA Command Example (TypeScript) ### Description Executes a Lua script in Redis using its SHA1 digest. ### Method POST ### Endpoint /v2/redis/evalsha ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sha1** (string) - Required - The SHA1 hash of the script. - **keys** (string[]) - Optional - Keys that the script will access. - **args** (any[]) - Optional - Arguments to pass to the script. ### Request Example ```json { "sha1": "fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", "keys": [], "args": ["hello"] } ``` ### Response #### Success Response (200) - **type** (any) - The result returned by the Lua script. #### Response Example ```json "hello" ``` ``` -------------------------------- ### Flush Database using Python FLUSHDB Command Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples of executing the FLUSHDB command in Python, demonstrating both synchronous and asynchronous modes for clearing all keys from the selected database. Note: The example uses `flushall()` which clears all databases. ```python redis.flushall() ``` ```python redis.flushall(flush_type="ASYNC") ``` -------------------------------- ### Redis ZINTERSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt This entry represents the ZINTERSTORE command in Redis. No specific code example or detailed description was provided in the source. ```Redis ZINTERSTORE ``` -------------------------------- ### Connect and Use upstash-redis Client with Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/howto/connectwithupstashredis Shows how to initialize the upstash-redis client by automatically loading credentials from environment variables (UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN). It then performs a GET operation. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv()(async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` -------------------------------- ### Redis GET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt This section outlines the API specification for the Redis GET command. It details the required parameters and the structure of the expected response when querying a key in Redis. ```APIDOC ## Redis GET Command API Reference ### Description This section outlines the API specification for the Redis GET command. It details the required parameters and the structure of the expected response when querying a key in Redis. ### GET Command - **Description**: Return the value of the specified key or `null` if the key doesn't exist. - **Arguments**: - **key** (string): Required - The key to get. - **Response**: - **Description**: The value stored at the key or `null` if the key doesn't exist. - **Required**: true ``` -------------------------------- ### Initialize Cloudflare Worker Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Cloudflare Worker project using the `wrangler init` CLI. This process includes setting up the project directory, selecting a template, choosing a language (TypeScript), and installing dependencies. ```shell npx wrangler init ╭ Create an application with Cloudflare Step 1 of 3 │ ├ In which directory do you want to create your application? │ dir ./greetings-cloudflare │ ├ What would you like to start with? │ category Hello World example │ ├ Which template would you like to use? │ type Hello World Worker │ ├ Which language do you want to use? │ lang TypeScript │ ├ Copying template files │ files copied to project directory │ ├ Updating name in `package.json` │ updated `package.json` │ ╰ Application created ╭ Configuring your application for Cloudflare Step 2 of 3 │ ├ Installing @cloudflare/workers-types │ installed via npm │ ├ Adding latest types to `tsconfig.json` │ added @cloudflare/workers-types/2023-07-01 │ ├ Retrieving current workerd compatibility date │ compatibility date 2024-10-22 │ ├ Do you want to use git for version control? │ no git │ ╰ Application configured ``` -------------------------------- ### REST API: SET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides an example of sending a Redis SET command as a JSON array in the body of an HTTP POST request to the Upstash REST API. Includes setting a key-value pair with an expiration. ```shell curl -X POST -d '["SET", "foo", "bar", "EX", 100]' https://us1-merry-cat-32748.upstash.io \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ``` -------------------------------- ### RPUSH Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/rpush Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. It shows the command's usage and verifies the list's state after the operation. This requires the 'redis' library. ```python assert redis.rpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] ``` -------------------------------- ### Initialize Serverless Node.js Project Source: https://upstash.com/docs/redis/overall/llms-txt Interactive command-line process to initialize a new Serverless project for AWS Node.js. It guides the user through selecting options like the template, runtime, and project name, resulting in a 'histogram-api' folder. ```text >> serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? histogram-api Project successfully created in 'histogram-api' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` -------------------------------- ### ACL RESTTOKEN Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Example of successfully using the `ACL RESTTOKEN` command via `redis-cli` to generate a REST token. The command takes a username and password, returning the new REST token as a string. ```APIDOC ## ACL RESTTOKEN ### Description Generates a REST token for an ACL user. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments - **username** (string) - Required - The username of the ACL user. - **password** (string) - Required - The password for the ACL user. ### Request Example ```shell redis-cli> ACL RESTTOKEN default YOUR_PASSWORD ``` ### Response #### Success Response (200) - **token** (string) - The generated REST token. #### Response Example ``` "AYNgAS2553feg6a2d9842h2a0gcdb5f8efe9934DQ=" ``` ``` -------------------------------- ### Create Next.js Application Source: https://upstash.com/docs/redis/overall/llms-txt This shell command initializes a new Next.js application using `create-next-app` and then navigates into the newly created project directory named 'my-app'. ```shell npx create-next-app@latest cd my-app ``` -------------------------------- ### Define Dockerfile for Application Container Source: https://upstash.com/docs/redis/overall/llms-txt A Dockerfile snippet that specifies instructions for building a Docker image. It includes copying the application's source code into the container and defining the command to run when the container starts, suitable for deploying applications. ```Dockerfile COPY . ./ CMD [ "npm", "start" ] ``` -------------------------------- ### Python LINSERT Example for Upstash Redis Source: https://upstash.com/docs/redis/sdks/py/commands/list/linsert This Python code snippet demonstrates how to use the LINSERT command with Upstash Redis. It first pushes elements to a list and then inserts a new element before a specified pivot element. ```python redis.rpush("key", "a", "b", "c") redis.linsert("key", "before", "b", "x") ``` -------------------------------- ### DBSIZE Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documents the DBSIZE command, its arguments, response type, and provides a TypeScript example for usage with a Redis client. ```APIDOC ## DBSIZE Command ### Description Retrieves the number of keys in the database. ### Method GET (or equivalent client method) ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const keys = await redis.dbsize(); console.log(keys) // Example Output: 20 ``` ### Response #### Success Response (200) - **type** (integer) - The number of keys in the database. ``` -------------------------------- ### Initialize Serverless Framework Project (AWS Node.js) Source: https://upstash.com/docs/redis/tutorials/using_serverless_framework Scaffolds a new Serverless Framework project for AWS using Node.js and an HTTP API template. This sets up the basic structure for a serverless application. ```shell ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · counter-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · counter-serverless Your new Service "counter-serverless" is ready. Here are next steps: • Open Service Directory: cd counter-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ``` -------------------------------- ### Instantiate Redis Client in Fastly Source: https://upstash.com/docs/redis/sdks/ts/deployment Details how to create a Redis client for Fastly Compute@Edge. It highlights the need to configure a backend in `fastly.toml` and shows manual instantiation with URL, token, and backend name. ```typescript import { Redis } from "@upstash/redis/fastly" const redis = new Redis({ url: , token: , backend: , }) ``` -------------------------------- ### Connect to Upstash Redis with Node.js Source: https://upstash.com/docs/redis/quickstarts/koyeb Demonstrates how to initialize the Upstash Redis client using environment variables for URL and token. It then performs a 'set' operation to store a key-value pair. This snippet requires the `@upstash/redis` package. ```javascript import { Redis } from "@upstash/redis"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }); const data = await redis.set("foo", "bar"); ``` -------------------------------- ### Create Laravel Project and Navigate Source: https://upstash.com/docs/redis/tutorials/laravel_caching Initializes a new Laravel project named 'todo-cache' and navigates into the project directory. This is the first step in setting up the Laravel application. ```shell laravel new todo-cache cd todo-cache ``` -------------------------------- ### TypeScript LTRIM Command Example (Upstash Redis) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing a list with `lpush` and then trimming it to a specific range using `ltrim` in TypeScript with Upstash Redis. ```typescript await redis.lpush("key", "a", "b", "c", "d"); await redis.ltrim("key", 1, 2); // the list is now ["b", "c"] ``` -------------------------------- ### Python SETBIT Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the use of the `setbit` method in Python to manipulate bits within a Redis string. This example sets a specific bit at a given offset to 1 and captures the original bit value. Requires a Redis client instance. ```python original_bit = redis.setbit(key, 4, 1) ``` -------------------------------- ### Import isomorphic-fetch in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/troubleshooting After installing `isomorphic-fetch`, import it in your TypeScript project to enable the `fetch` API. This is typically done alongside initializing the Upstash Redis client. ```typescript import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` -------------------------------- ### Redis BITPOS Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitpos Demonstrates how to use the BITPOS command in Python to find the position of the first set (1) or clear (0) bit within a specified range of a Redis string key. It requires a Redis client connection. ```python redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) assert redis.bitpos("mykey", 1) == 7 assert redis.bitpos("mykey", 0) == 0 # With a range assert redis.bitpos("mykey", 1, 0, 2) == 0 assert redis.bitpos("mykey", 1, 2, 3) == -1 ``` ```python redis.bitpos("key", 1, 5, 20) ``` -------------------------------- ### TypeScript LPOS Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates various usages of the LPOS command in TypeScript, including basic usage, using the 'rank' option, and using the 'count' option. ```APIDOC ## TypeScript LPOS Command Examples ### Description Demonstrates various usages of the LPOS command in TypeScript, including basic usage, using the 'rank' option, and using the 'count' option. ### Usage Examples **Basic Usage:** ```ts await redis.rpush("key", "a", "b", "c"); const index = await redis.lpos("key", "b"); console.log(index); // 1 ``` **With 'rank' option:** ```ts await redis.rpush("key", "a", "b", "c", "b"); const index = await redis.lpos("key", "b", { rank: 2 }); console.log(index); // 3 ``` **With 'count' option:** ```ts await redis.rpush("key", "a", "b", "b"); const positions = await redis.lpos("key", "b", { count: 2 }); console.log(positions); // [1, 2] ``` ``` -------------------------------- ### HKEYS TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `hset` command to set a hash and then retrieve all its field names using `hkeys` in TypeScript, showing the expected output. ```APIDOC ## HKEYS ### Description Returns all field names in the hash stored at key. ### Method `HKEYS` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```ts await redis.hset("key", { id: 1, username: "chronark", }); const fields = await redis.hkeys("key"); console.log(fields); // ["id", "username"] ``` ### Response #### Success Response (200) - fields (string[]) - A list of field names in the hash. ``` -------------------------------- ### ZPOPMAX TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to call the ZPOPMAX command using the Upstash Redis client in TypeScript, retrieving a specified number of elements. ```APIDOC ## ZPOPMAX ### Description Removes and returns the element with the highest score from a sorted set. ### Method `ZPOPMAX` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript const popped = await redis.zpopmax("key", 4); ``` ### Response #### Success Response (200) - elements (Array<[member: string, score: number]>) - An array of elements popped from the sorted set. ``` -------------------------------- ### Upstash Redis Worker Code Example (TypeScript/JavaScript) Source: https://upstash.com/docs/redis/quickstarts/cloudflareworkers A Cloudflare Worker template demonstrating how to connect to Upstash Redis and increment a counter. It uses environment variables for credentials and the Upstash Redis SDK. This example works with both TypeScript and JavaScript. ```typescript import { Redis } from "@upstash/redis/cloudflare"; export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; } export default { async fetch(request, env, ctx): Promise { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, } satisfies ExportedHandler; ``` ```javascript import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env, ctx) { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, }; ``` -------------------------------- ### Upstash Redis XREVRANGE Command Examples (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrevrange Demonstrates how to use the XREVRANGE command in Python to fetch stream entries. It covers fetching all entries in reverse order, limiting the count, and specifying a particular ID range. ```python result = redis.xrevrange("mystream", "+", "-") ``` ```python result = redis.xrevrange("mystream", "+", "-", count=2) ``` ```python result = redis.xrevrange("mystream", end="1638360173533-2", start="1638360173533-0") ``` -------------------------------- ### Create Phoenix App with No Ecto (Elixir) Source: https://upstash.com/docs/redis/quickstarts/elixir Command to create a new Elixir Phoenix application without the Ecto ORM, as Redis will be used as the primary datastore. This simplifies setup when not requiring a relational database. ```bash mix phx.new redix_demo --no-ecto ``` -------------------------------- ### Shell: ACL RESTTOKEN Command Error Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows an example of an error response from the `ACL RESTTOKEN` command in redis-cli when authentication fails due to an incorrect password or a non-existent user. ```shell redis-cli> ACL RESTTOKEN upstash fakepass (error) ERR Wrong password or user "upstash" does not exist ``` -------------------------------- ### TypeScript SCRIPT EXISTS Example Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the `scriptExists` method with the Upstash Redis client in TypeScript. It takes one or more SHA1 hashes as input and returns an array indicating the existence of each script. ```typescript await redis.scriptExists("", "") // Returns 1 // [1, 0] ``` -------------------------------- ### Upstash Redis HVALS Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using `hset` to populate a Redis hash and then retrieving all its values using the `hvals` command in Python. Includes an assertion for verification. ```Python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hvals("myhash") == ["Hello", "World"] ``` -------------------------------- ### Create React App for Notification API Source: https://upstash.com/docs/redis/tutorials/notification This command initializes a new React application using create-react-app. This application will serve as the frontend for the serverless notification system. ```shell npx create-react-app serverless-notification-api ``` -------------------------------- ### Connect to Upstash Redis using ioredis (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Example showing how to connect to an Upstash Redis database using the `ioredis` library in Node.js and perform basic set/get operations. ```APIDOC ## Connect and Basic Operations with ioredis ### Description Establishes a secure connection to Upstash Redis using the provided endpoint, port, and password, then demonstrates setting and retrieving a key-value pair. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```javascript const Redis = require("ioredis"); let client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); await client.set("foo", "bar"); let x = await client.get("foo"); console.log(x); ``` ### Response N/A (Code Example) ``` -------------------------------- ### ZLEXCOUNT Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zlexcount Demonstrates how to use the ZLEXCOUNT command in Python to count elements in a sorted set within a lexicographical range. It first adds elements to a set and then uses ZLEXCOUNT with inclusive bounds. ```python redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zlexcount("myset", "-", "+") == 3 ``` -------------------------------- ### Redis GET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Outlines the API specification for the Redis GET command. Details required parameters (key) and the structure of the expected response (value or null), used for retrieving data from Redis. ```APIDOC GET Command: Description: Return the value of the specified key or `null` if the key doesn't exist. Arguments: key: Type: string Required: true Description: The key to get. Response: Description: The value stored at the key or `null` if the key doesn't exist. Required: true ``` -------------------------------- ### Run FastAPI Application with Uvicorn Source: https://upstash.com/docs/redis/tutorials/python_fastapi_caching Starts the FastAPI application using the Uvicorn ASGI server. This command enables hot-reloading, so changes to the code will automatically restart the server. ```shell uvicorn main:app --reload ``` -------------------------------- ### Run Express Application (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Executes an 'index.js' file using Node.js to start an Express server, making the application accessible on the configured port. ```bash node index.js ``` -------------------------------- ### Python Examples for Redis SET Command Source: https://upstash.com/docs/redis/overall/llms-txt Python code snippets demonstrating various uses of the Redis SET command, including basic set operations, conditional setting (NX/XX), setting expiration times (EX/PX), and retrieving the previous value. ```python assert redis.set("key", "value") == True assert redis.get("key") == "value" ``` ```python # Only set the key if it does not already exist. assert redis.set("key", "value", nx=True) == False # Only set the key if it already exists. assert redis.set("key", "value", xx=True) == True ``` ```python # Set the key to expire in 10 seconds. assert redis.set("key", "value", ex=10) == True # Set the key to expire in 10000 milliseconds. assert redis.set("key", "value", px=10000) == True ``` ```python # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ``` -------------------------------- ### Python JSON.ARRPOP Example (First Element) Source: https://upstash.com/docs/redis/overall/llms-txt This Python example uses `redis.json.arrpop` to remove and retrieve the first element from a JSON array by providing an explicit index of 0. It requires the key and JSON array path. ```python firstElement = redis.json.arrpop("key", "$.path.to.array", 0) ``` -------------------------------- ### Redis SETRANGE Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/string/setrange Demonstrates how to use the SETRANGE command in Redis with Python. It sets an initial value for a key, then uses SETRANGE to modify a part of that value, and finally retrieves the modified value. This requires a Redis client library for Python. ```python redis.set("key", "Hello World") assert redis.setrange("key", 6, "Redis") == 11 assert redis.get("key") == "Hello Redis" ``` -------------------------------- ### GET /keys Source: https://upstash.com/docs/redis/sdks/py/commands/generic/keys Fetches all keys matching a given pattern. This command can be blocking and has limitations on dataset size. ```APIDOC ## GET /keys ### Description Fetches all keys matching a glob-style pattern. Use `*` to match all keys. This command can block the database for an extended period, especially with large datasets, and will return an error for databases containing more than 100,000 entries. Consider using SCAN for production environments. ### Method GET ### Endpoint /keys ### Parameters #### Query Parameters - **match** (str) - Required - A glob-style pattern. Use `*` to match all keys. ### Request Example ```py redis.keys("prefix*") redis.keys("*") ``` ### Response #### Success Response (200) - **keys** (List[str]) - Array of keys matching the pattern. #### Response Example ```json { "keys": ["key1", "key2", "key3"] } ``` ``` -------------------------------- ### Python XRANGE Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the usage of the `xrange` command in Python to retrieve entries from a Redis stream. This snippet shows the typical output format of stream data. ```python entries = redis.xrange(key, "-", "+") print(entries) # { # "1548149259438-0": { # "field1": "value1", # "field2": "value2" # }, # "1548149259438-1": { # "field1": "value3", # "field2": "value4" # } # } ``` -------------------------------- ### DECRBY TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the DECRBY command with the Upstash Redis client in TypeScript, showing key initialization, decrementing, and the resulting value. ```APIDOC ## DECRBY ### Description Decrements the integer value of a key by a specified amount. ### Method `DECRBY` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript await redis.set("key", 6); await redis.decrby("key", 4); // returns 2 ``` ### Response #### Success Response (200) - value (integer) - The value of the key after the decrement. ``` -------------------------------- ### Python Example for DECR Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the DECR command in Python with the 'redis' client, including setting an initial value and asserting the decremented result. ```APIDOC ## DECR Command Example in Python ### Description Decrements the integer value of a key by one. ### Method ``` redis.decr(key) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.set("key", 6) assert redis.decr("key") == 5 ``` ### Response #### Success Response (200) The integer value of the key after being decremented. #### Response Example ```json 5 ``` ``` -------------------------------- ### Python Example for ZCARD Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the Redis ZCARD command in Python with the Upstash Redis client. It shows adding elements to a sorted set and verifying the count. ```Python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zcard("myset") == 3 ``` -------------------------------- ### Run Python Script (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Provides the command-line instruction to execute a Python script. Assumes Python is installed and the script is in the current directory. ```bash python your_script_name.py ``` -------------------------------- ### Execute Flask Web Application Source: https://upstash.com/docs/redis/overall/llms-txt This command runs the `app.py` script, starting the Flask development server. Once running, the application will be accessible locally, allowing users to interact with the Redis-backed counter functionality. ```APIDOC ## Run Flask Application ### Description Starts the Flask development server for the Redis-backed application. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```bash python app.py ``` ### Response N/A (Server output will be displayed in the console) ### Notes This command assumes `app.py` is in the current directory and Flask is installed. ``` -------------------------------- ### SRANDMEMBER Usage Examples in TypeScript (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt These TypeScript examples demonstrate the usage of the `srandmember` command with Upstash Redis. They show how to retrieve a single random member and multiple random members from a Redis set. ```typescript await redis.sadd("set", "a", "b", "c"); const member = await redis.srandmember("set"); console.log(member); // "a" ``` ```typescript await redis.sadd("set", "a", "b", "c"); const members = await redis.srandmember("set", 2); console.log(members); // ["a", "b"] ``` -------------------------------- ### ZUNIONSTORE Command Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates several ways to use the ZUNIONSTORE command in TypeScript with Upstash Redis. Examples include basic set union, applying weights to input sets, and using different aggregation methods like 'sum'. This command merges multiple sorted sets into a new sorted set. ```typescript await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore("destination", 2, ["key1", "key2"]); console.log(res) // 2 ``` ```typescript await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { weights: [2, 3] }, ); console.log(res) // 2 ``` ```typescript await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { aggregate: "sum" }, ); console.log(res) // 2 ``` -------------------------------- ### ZINTER with Weights Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to perform a ZINTER (sorted set intersection) operation in Python with custom weights. This example uses `zadd` to populate two sets and then `zinter` with `weights` and `aggregate` options to calculate the result. ```Python redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` -------------------------------- ### Configure Redix Client Instance (Elixir) Source: https://upstash.com/docs/redis/quickstarts/elixir Adds a global Redix client instance to the application's children list in `application.ex`. It configures the connection using the extracted host, port, and password, including `socket_opts` for IPv6 compatibility. ```elixir children = [ # ... { Redix, name: :redix, host: host, port: port, password: password, socket_opts: [:inet6] } ] ``` -------------------------------- ### LREM TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript code example demonstrating how to use the LREM command with an Upstash Redis client. It shows pushing multiple elements to a list and then removing specific occurrences of an element, logging the count of removed items. ```APIDOC ## LREM ### Description Removes occurrences of a value from a list. ### Method `LREM` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```ts await redis.lpush("key", "a", "a", "b", "b", "c"); const removed = await redis.lrem("key", 4, "b"); console.log(removed) // 2 ``` ### Response #### Success Response (200) - count (integer) - The number of removed elements. ``` -------------------------------- ### Python Example for SUNION Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `SUNION` command with a Python Redis client. It adds elements to two sets and then performs a union operation. ```APIDOC ## SUNION Command (Python) ### Description Returns the union of all the given sets. This command computes the union of sets stored at the keys. ### Method `redis.sunion(key1: str, key2: str, ...keys: str): Set[str] ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.sadd("key1", "a", "b", "c") redis.sadd("key2", "c", "d", "e") union_set = redis.sunion("key1", "key2") print(union_set) # {'a', 'b', 'c', 'd', 'e'} ``` ### Response #### Success Response - **Set[str]**: A set containing all elements from the input sets. #### Response Example ```json {"a", "b", "c", "d", "e"} ``` ``` -------------------------------- ### Create New Laravel Project Source: https://upstash.com/docs/redis/quickstarts/laravel Creates a new Laravel project using either the Laravel CLI or Composer. It then navigates into the project directory. ```shell laravel new example-app cd example-app ``` ```shell composer create-project laravel/laravel example-app cd example-app ``` -------------------------------- ### TypeScript Example for INCRBYFLOAT Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `incrbyfloat` command in TypeScript with an Upstash Redis client, showing setting a key and then incrementing its float value. ```APIDOC ## TypeScript INCRBYFLOAT Example ### Description Increment the value of a string key in Redis by a floating-point number. ### Method INCRBYFLOAT ### Endpoint N/A (Command specific) ### Parameters #### Query Parameters - **key** (string) - The key to increment. - **increment** (number) - The float value to add to the key. ### Request Example ```typescript await redis.set("key", 6); await redis.incrbyfloat("key", 4.5); // returns 10.5 ``` ### Response #### Success Response (200) - **value** (number) - The new value of the key after incrementing. ``` -------------------------------- ### Upstash Redis ZADD Command Examples (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zadd Demonstrates various ways to use the ZADD command in Upstash Redis with TypeScript. This includes basic addition, updating existing members, adding only new members, and using options like 'ch', 'incr', 'gt', and 'lt'. The 'redis' object is assumed to be an initialized Upstash Redis client. ```typescript await redis.zadd( "key", { score: 2, member: "member" }, { score: 3, member: "member2"} ); ``` ```typescript await redis.zadd( "key", { xx: true }, { score: 2, member: "member" }, ) ``` ```typescript await redis.zadd( "key", { nx: true }, { score: 2, member: "member" }, ) ``` ```typescript await redis.zadd( "key", { ch: true }, { score: 2, member: "member" }, ) ``` ```typescript await redis.zadd( "key", { cincrh: true }, { score: 2, member: "member" }, ) ``` ```typescript await redis.zadd( "key", { gt: true }, { score: 2, member: "member" }, ) ``` ```typescript await redis.zadd( "key", { lt: true }, { score: 2, member: "member" }, ) ``` -------------------------------- ### TypeScript HDEL Redis Command Example Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript snippet illustrates the use of the HDEL command with the Upstash Redis client. It shows how to remove one or more fields from a hash stored at a given key, with an example return value. ```typescript await redis.hdel(key, 'field1', 'field2'); // returns 5 ``` -------------------------------- ### PUBLISH Command (TypeScript SDK) Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to publish a message to a Redis channel using the `redis.publish` method in TypeScript, capturing the number of listeners. ```APIDOC ## PUBLISH (TypeScript SDK) ### Description Posts a message to a specified channel. Returns the number of clients that received the message. ### Method SDK Method Call ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments (for `redis.publish`) - **channel** (string) - Required - The name of the channel to publish to. - **message** (string) - Required - The message content to send. ### Request Example (TypeScript) ```typescript import redis from 'redis'; async function publishMessage() { const client = redis.createClient({ url: 'YOUR_REDIS_URL' }); await client.connect(); const channel = 'my-topic'; const message = 'my-message'; try { const listeners = await client.publish(channel, message); console.log(`Message published to ${channel}. Listeners: ${listeners}`); } catch (error) { console.error('Error publishing message:', error); } finally { await client.disconnect(); } } publishMessage(); ``` ### Response #### Success Response (200) - **listeners** (number) - The number of clients that received the message. #### Response Example ```javascript // If there are 2 clients subscribed to 'my-topic': // Message published to my-topic. Listeners: 2 ``` ``` -------------------------------- ### LINDEX Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the LINDEX command with Upstash Redis in TypeScript, demonstrating how to push elements to a list and then retrieve a specific element by its index. ```APIDOC ## LINDEX Command Example (TypeScript) ### Description Illustrates using the LINDEX command in TypeScript to retrieve an element from a list at a specific index. It first pushes elements to a list and then fetches one based on its position. ### Method `LINDEX` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client instance in TypeScript // Push elements to a list await redis.rpush("key", "a", "b", "c"); // Retrieve the element at index 0 const element = await redis.lindex("key", 0); console.log(element); // Outputs: "a" ``` ### Response #### Success Response Returns the element at the specified index, or `null` if the index is out of range. #### Response Example ```json "a" // The element at index 0 ``` ``` -------------------------------- ### Python JSON.ARRPOP Example (Last Element) Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use `redis.json.arrpop` in Python to remove and retrieve the last element from a specified JSON array path. It requires the key and JSON array path as input. ```python element = redis.json.arrpop("key", "$.path.to.array") ``` -------------------------------- ### List Container Images with gcloud Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions Command to list all container images available in your Google Container Registry. Useful for verifying that your image was built successfully. ```bash gcloud container images list ``` -------------------------------- ### Get Set Cardinality with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the `SCARD` command in TypeScript to get the number of members in a set. It first adds members using `SADD` and then retrieves the cardinality. ```typescript await redis.sadd("key", "a", "b", "c"); const cardinality = await redis.scard("key"); console.log(cardinality); // 3 ``` -------------------------------- ### Run Supabase Function Locally Source: https://upstash.com/docs/redis/overall/llms-txt Starts the Supabase local development environment and serves the 'upstash-redis-counter' function locally, allowing for testing without JWT verification and using a specific environment file. ```APIDOC ## Run Supabase Function Locally ### Description This command starts the Supabase local development environment and serves a specified function locally with options to disable JWT verification and use a custom environment file. ### Command ```bash supabase start supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env ``` ``` -------------------------------- ### Upsert Data with Upstash Search Client Source: https://upstash.com/docs/redis/howto/vercelintegration Shows how to initialize the Upstash Search client and upsert data into a specified index. Requires the '@upstash/search' package and UPSTASH_SEARCH_REST_URL/TOKEN environment variables. ```typescript import { Search } from "@upstash/search"; const client = new Search({ url: process.env.UPSTASH_SEARCH_REST_URL, token: process.env.UPSTASH_SEARCH_REST_TOKEN, }); const index = client.index("my-index"); await index.upsert({ id: "1", content: { text: "Hello world!" }, metadata: { category: "greeting" } }); ``` -------------------------------- ### Add Bull Task Queue to Node.js Project Source: https://upstash.com/docs/redis/tutorials/job_processing Installs the Bull library, a popular Redis-based queue for Node.js, as a dependency for the project. This enables the use of job queues. ```shell npm install bull ``` -------------------------------- ### Build Java Project with Maven Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Builds the Java project using Maven. This command compiles the code, runs tests, and packages the application artifact, typically a JAR file. ```shell mvn clean install ``` -------------------------------- ### Publish Messages with Upstash QStash Client Source: https://upstash.com/docs/redis/overall/llms-txt This example shows how to create an Upstash QStash client and publish a JSON message. The client is initialized with a token from `process.env.QSTASH_TOKEN`. It demonstrates publishing a message to a specified URL with a JSON body. ```APIDOC ## Publish JSON Message with QStash Client ### Description Publishes a JSON message to a specified URL using the Upstash QStash client. ### Method POST (Implicitly, via QStash client method) ### Endpoint (Not directly exposed, handled by the client library) ### Parameters #### Environment Variables - **QSTASH_TOKEN** (string) - Required - The authentication token for the QStash client. #### Request Body (JSON) - **url** (string) - Required - The URL to which the message will be published. - **body** (object) - Required - The JSON payload of the message. ### Request Example ```json { "url": "https://my-api...", "body": { "hello": "world" } } ``` ### Response #### Success Response (200 OK) (Details depend on the QStash service response, typically an acknowledgment.) #### Response Example (Not explicitly provided in the source, but would be a success confirmation.) ``` -------------------------------- ### Python TOUCH Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the use of the TOUCH command in Python to update the last access time for one or more specified keys in Redis. ```python redis.touch("key1", "key2", "key3") ``` -------------------------------- ### TypeScript Example: Setting PEXPIRE on a Redis Key (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates using the `pexpire` method to set a key's expiration time in milliseconds using the Upstash Redis client. It sets a 1-minute expiration. ```typescript await redis.pexpire(key, 60_000); // 1 minute ``` -------------------------------- ### Python Example for UNLINK Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the UNLINK command with the Upstash Redis client in Python, asserting the number of keys unlinked. ```APIDOC ## UNLINK Command Example in Python ### Description Removes one or more keys from the Redis store. ### Method ``` redis.unlink(key1, key2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python assert redis.unlink("key1", "key2", "key3") == 3 ``` ### Response #### Success Response (200) An integer representing the number of keys unlinked. #### Response Example ```json 3 ``` ``` -------------------------------- ### BITOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the Redis `BITOP` command, including its supported operations, required keys, and the format of its response. ```APIDOC ## BITOP Command API Reference ### Description Performs bitwise operations on multiple keys (or Redis strings) and stores the result in a destination key. ### Method `BITOP operation destinationKey key [key ...]` ### Endpoint Not applicable (Redis command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```APIDOC BITOP AND destkey key1 key2 BITOP OR destkey key1 key2 BITOP XOR destkey key1 key2 BITOP NOT destkey key1 ``` ### Response #### Success Response - `type` (integer) - The size of the string stored in the destination key. ``` -------------------------------- ### Ratelimit blockUntilReady Usage Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use `ratelimit.blockUntilReady` to create a ratelimiter and wait for a request to be allowed. It shows initializing a ratelimiter and handling the success or failure of the `blockUntilReady` call. ```APIDOC ## Ratelimit blockUntilReady Usage Example (TypeScript) ### Description This example shows how to set up a rate limiter using `blockUntilReady` and wait for a request to be permitted. It handles the outcome of the `blockUntilReady` operation. ### Method `ratelimit.blockUntilReady(identifier, timeout)` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30_000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ``` ### Response #### Success Response - `success` (boolean) - Indicates if the request was allowed within the timeout period. ``` -------------------------------- ### SMISMEMBER Command Source: https://upstash.com/docs/redis/overall/llms-txt Information for the SMISMEMBER command. No specific description or usage examples were provided. ```APIDOC ## SMISMEMBER Command ### Description No description provided. ### Method POST (Implied by command format) ### Endpoint /redis/v1/command (Implied by context) ### Request Body Example ```json { "command": "SMISMEMBER", "key": "your_set_key", "members": ["member1", "member2"] } ``` ### Response Example ```json { "result": [1, 0] } ``` ``` -------------------------------- ### Django View to Increment Redis Counter Source: https://upstash.com/docs/redis/quickstarts/django Defines a Django view that connects to Upstash Redis, increments a 'counter' key, and returns the updated count in an HTTP response. It utilizes the `upstash-redis` client. ```python from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') return HttpResponse(f'Page visited {count} times.') ``` -------------------------------- ### TypeScript Example for JSON.MGET Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `redis.json.mget` method in TypeScript to retrieve values from multiple JSON documents at a specified path. ```APIDOC ## Get Multiple JSON Values (JSON.MGET) ### Description Retrieves values from multiple JSON documents at a specified path using JSON.MGET. ### Method POST ### Endpoint /api/redis/json/mget ### Parameters #### Request Body - **keys** (string[]) - Required - An array of keys for the JSON documents. - **path** (string) - Required - The JSON path to retrieve values from. ### Request Example ```json { "keys": ["key1", "key2"], "path": "$.path.to.somewhere" } ``` ### Response #### Success Response (200) - **values** (array) - An array containing the retrieved values. #### Response Example ```json { "values": ["value1", "value2"] } ``` ``` -------------------------------- ### Upstash Redis FLUSHALL Command Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Examples for using the FLUSHALL command with Upstash Redis in TypeScript. It covers both synchronous and asynchronous execution modes for clearing all keys in the database. Requires the Upstash Redis TypeScript client. ```ts await redis.flushall(); ``` ```ts await redis.flushall({async: true}) ``` -------------------------------- ### Get List Length using LLEN (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the `llen` command in TypeScript to get the number of elements in a Redis list. It shows pushing elements and then retrieving the list's length. ```typescript await redis.rpush("key", "a", "b", "c"); const length = await redis.llen("key"); console.log(length); // 3 ``` -------------------------------- ### Python Example for Redis DEL Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `delete` method with a Python Redis client to remove multiple keys and verify their successful removal. ```APIDOC ## Python Example for Redis DEL Command ### Description Demonstrates how to use the `delete` method with a Python Redis client to remove multiple keys and verify their successful removal. ### Language Python ### Code ```python redis.set("key1", "Hello") redis.set("key2", "World") redis.delete("key1", "key2") assert redis.get("key1") is None assert redis.get("key2") is None ``` ``` -------------------------------- ### Initialize Upstash Redis Client (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates direct configuration of the Upstash Redis client in TypeScript using REST URL and token. It performs an asynchronous GET operation and logs the result or errors. No external dependencies are required beyond the `@upstash/redis` package. ```typescript import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN" }); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` -------------------------------- ### GET Command with Base64 Encoded Response Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to request a base64 encoded response from the Upstash REST API for a GET command by including the `Upstash-Encoding: base64` header. The actual value will be base64 encoded. ```APIDOC ## GET /:key ### Description Retrieves the value associated with a given key. Supports base64 encoded responses. ### Method GET ### Endpoint `/` ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Upstash-Encoding** (string) - Optional - Specifies the encoding for the response. Set to `base64` for base64 encoded output. ### Request Example ```shell curl https://your-upstash-redis-url.com/GET/foo \ -H "Authorization: Bearer YOUR_AUTH_TOKEN" \ -H "Upstash-Encoding: base64" ``` ### Response #### Success Response (200) - **value** (string) - The value of the key, potentially base64 encoded if requested. #### Response Example ```json { "result": "encoded_value_here" } ``` ``` -------------------------------- ### LTRIM Redis Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the LTRIM Redis command, outlining its required arguments (key, start, stop), their types, and the boolean response indicating successful trimming. ```APIDOC ## LTRIM Redis Command API Documentation ### Description Trims a list stored at a key so that it contains only the specified range of elements. ### Method POST ### Endpoint `/redis/commands ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "command": "ltrim", "key": "", "start": , "stop": } ``` ### Parameters Details #### Key - **key** (str) - Required - The key of the list. - **start** (int) - Required - The index of the first element to keep. - **stop** (int) - Required - The index of the last element to keep. ### Request Example ```python # Assuming 'redis' is a configured Redis client instance success = redis.ltrim('my_list', 0, 5) ``` ### Response #### Success Response (200) - **bool**: Returns `True` if the list was trimmed, `False` otherwise. #### Response Example ```json { "trimmed": true } ``` ``` -------------------------------- ### Example Usage of HEXPIREAT with Upstash Redis in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates how to use the `hexpireat` command with the Upstash Redis client. It sets a value in a hash, applies an expiration to a specific field using a Unix timestamp, and logs the result. ```APIDOC ## TypeScript HEXPIREAT Example ### Description Set a specific time at which the given hash field will expire, specified in Unix time format (seconds). ### Method HEXPIREAT ### Endpoint N/A (Command specific) ### Parameters #### Query Parameters - **key** (string) - The key of the hash. - **field** (string) - The field within the hash to set expiration for. - **timestamp** (number) - The Unix timestamp (seconds) at which the field will expire. ### Request Example ```typescript await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hexpireat("my-key", "my-field", Math.floor(Date.now() / 1000) + 10); console.log(expirationSet); // [1] ``` ### Response #### Success Response (200) - **result** (number) - 1 if the time was added. 0 if the field does not exist or the time could not be added. ``` -------------------------------- ### Start FastAPI Development Server Source: https://upstash.com/docs/redis/overall/llms-txt This command initiates the FastAPI application in development mode. The --reload flag enables automatic server restarts upon code changes, facilitating rapid development and testing. ```APIDOC ## Start FastAPI Development Server ### Description Starts the Uvicorn server for a FastAPI application in development mode with automatic reloading on code changes. ### Method Shell command ### Endpoint N/A ### Parameters None ### Request Example ```bash uvicorn main:app --reload ``` ### Response N/A ``` -------------------------------- ### Connect to Redis Locally in Node.js (JavaScript) Source: https://upstash.com/docs/redis/quickstarts/fly Example Node.js code demonstrating how to connect to a Redis instance using a local URL obtained from 'fly redis connect'. It uses an environment variable to switch between the local development URL and a production Redis URL. Requires the 'redis' package. ```javascript const redis = require("redis"); // Local Redis URL for development const LOCAL_REDIS_URL = 'redis://localhost:10000'; // Replace with your actual local address const REDIS_URL = process.env.NODE_ENV === 'development' ? LOCAL_REDIS_URL : process.env.REDIS_URL; const client = redis.createClient({ url: REDIS_URL }); client.on("error", function(error) { console.error(error); }); // Rest of your Redis-related code ``` -------------------------------- ### JSON Response for GET Command with Base64 Encoding Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the expected JSON response for a Redis GET command when the 'Upstash-Encoding: base64' header is utilized. The 'result' field contains a Base64 encoded string. ```json {"result":"YmFy"} ``` -------------------------------- ### Waiting Room for Next.js App with Edge Functions Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides a conceptual example for implementing a waiting room for a Next.js application using Edge Functions and Upstash Redis. This pattern helps manage high traffic on a Next.js site by controlling access. ```javascript export async function GET(request) { // Logic for waiting room return new Response('Waiting Room'); } ``` -------------------------------- ### Python Example for Redis RANDOMKEY Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the Redis RANDOMKEY command using the Upstash Python SDK. It shows the behavior when the database is empty and after keys have been added, asserting the return value. Requires the Upstash Redis Python client. ```Python assert redis.randomkey() is None redis.set("key1", "Hello") redis.set("key2", "World") assert redis.randomkey() is not None ``` -------------------------------- ### Run Express Application Source: https://upstash.com/docs/redis/overall/llms-txt Executes the 'index.js' file using Node.js to start the Express server, making the application accessible on the configured port (e.g., 3000). ```APIDOC ## Run Express Application ### Description Executes the 'index.js' file using Node.js to start the Express server. ### Command ```bash node index.js ``` ``` -------------------------------- ### SDIFFSTORE Command API Reference (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the `SDIFFSTORE` command in Python, outlining its required arguments and the structure of its integer response. ```APIDOC ## SDIFFSTORE Command API Reference (Python) ### Description Write the difference between sets to a new set. ### Method APICALL ### Endpoint /redis/sdiffstore ### Parameters #### Query Parameters - **destination** (str) - Required - The key of the set to store the resulting set in. - **keys** (List[str]) - Required - The keys of the sets to perform the difference operation on. ### Request Example ```json { "destination": "new_set_key", "keys": ["set1", "set2"] } ``` ### Response #### Success Response (200) - **Count** (int) - The number of elements in the resulting set. #### Response Example ```json 5 ``` ``` -------------------------------- ### Python Examples for Redis EVAL Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `redis.eval` method in Python, including evaluating a script that retrieves a key's value and passing arguments to a Lua script. ```APIDOC ## Evaluate Lua Script (GET example) ### Description Evaluates a Lua script that retrieves a key's value. ### Method POST ### Endpoint /api/redis/eval ### Parameters #### Request Body - **script** (string) - Required - The Lua script to execute. - **keys** (string[]) - Required - An array of keys the script needs. ### Request Example ```json { "script": "local value = redis.call(\"GET\", KEYS[1])\nreturn value", "keys": ["mykey"] } ``` ### Response #### Success Response (200) - **result** (any) - The result of the script execution. #### Response Example ```json { "result": "Hello" } ``` ``` ```APIDOC ## Evaluate Lua Script (ARGV example) ### Description Evaluates a Lua script and passes arguments to it. ### Method POST ### Endpoint /api/redis/eval ### Parameters #### Request Body - **script** (string) - Required - The Lua script to execute. - **args** (string[]) - Required - An array of arguments to pass to the script. ### Request Example ```json { "script": "return ARGV[1]", "args": ["Hello"] } ``` ### Response #### Success Response (200) - **result** (any) - The result of the script execution. #### Response Example ```json { "result": "Hello" } ``` ``` -------------------------------- ### ZINTER with Weights Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to apply custom weights to input sets during a ZINTER operation in Python, demonstrating how weights influence the final aggregated scores. ```APIDOC ## ZINTER with Weights Example (Python) ### Description Compute the intersection of two sorted sets with custom weights and aggregation. ### Method APICALL ### Endpoint /redis/zinter ### Parameters #### Query Parameters - **keys** (string[]) - Required - The keys of the sorted sets to intersect. - **withscores** (boolean) - Optional - Whether to return scores along with members. - **aggregate** (string) - Optional - The aggregation method (e.g., 'SUM', 'MIN', 'MAX'). - **weights** (number[]) - Optional - The weights to apply to each key. ### Request Example ```json { "keys": ["key1", "key2"], "withscores": true, "aggregate": "SUM", "weights": [2, 3] } ``` ### Response #### Success Response (200) - **Result** (Array<[string, number]>) - An array of members and their scores in the intersection. #### Response Example ```json [["a", 5]] ``` ``` -------------------------------- ### ZPOPMIN TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZPOPMIN command with the Upstash Redis client in TypeScript to remove and retrieve elements from a sorted set. ```APIDOC ## ZPOPMIN ### Description Removes and returns the element with the lowest score from a sorted set. ### Method `ZPOPMIN` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript const popped = await redis.zpopmin("key", 4); ``` ### Response #### Success Response (200) - elements (Array<[member: string, score: number]>) - An array of elements popped from the sorted set. ``` -------------------------------- ### Example XReadGroup Cancellation Error Message Source: https://upstash.com/docs/redis/overall/llms-txt An example of a `ReplyError` encountered when a Redis stream consumer's Pending Entries List (PEL) limit is reached. This error indicates unacknowledged messages and potential stream processing issues. ```text ReplyError: ERR XReadGroup is cancelled. Pending Entries List limit per consumer is about to be reached. Limit: 1000, Current PEL size: 90, Requested Read: 20, Key: mstream, Group: group1, Consumer: consumer1. ``` -------------------------------- ### Redis SPOP Command Source: https://upstash.com/docs/redis/overall/llms-txt This entry represents the SPOP command in Redis. No specific code example or detailed description was provided in the source. ```Redis SPOP ``` -------------------------------- ### TypeScript ZRANGE Command Examples Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the ZRANGE command in TypeScript to retrieve members from a Redis sorted set. Examples cover basic range retrieval, retrieving members with their scores, and sorting by score. Requires a Redis client instance and involves asynchronous operations. ```typescript await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3) console.log(res) // ["m2"] ``` ```typescript await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3, { withScores: true }) console.log(res) // ["m2", 2] ``` ```typescript await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, ) const res = await redis.zrange("key", 1, 2, { byScore: true }) console.log(res) // ["m1", "m2"] ``` -------------------------------- ### Upstash Redis Transaction Example Response Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the expected JSON response structure for a transaction executed via Upstash Redis. It includes successful command results and an example of an error response when a command fails due to incorrect input type. ```json [ { "result": "OK" }, { "result": "OK" }, { "error": "ERR value is not an int or out of range" }, { "result": 2 } ] ``` -------------------------------- ### Create Upstash Redis Database Source: https://upstash.com/docs/redis/overall/llms-txt This snippet demonstrates how to create a new Upstash Redis database using the Upstash API. It includes both a CURL command example for direct execution and a structured API documentation outlining the endpoint, method, authentication, and request body parameters required for database creation. ```APIDOC ## Create Upstash Redis Database ### Description Creates a new Upstash Redis database with specified configuration. ### Method POST ### Endpoint https://api.upstash.com/v2/redis/database ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **name** (string) - Required - The name of the database. - **region** (string) - Required - The global region for the database (e.g., "global"). - **primary_region** (string) - Required - The primary AWS region for the database (e.g., "us-east-1"). - **read_regions** (array of strings) - Optional - List of AWS regions for read replicas (e.g., ["us-west-1","us-west-2"]). - **tls** (boolean) - Optional - Enable TLS for the database connection. ### Authentication Basic Authentication using `EMAIL:API_KEY`. ### Request Example ```bash curl -X POST \ https://api.upstash.com/v2/redis/database \ -u 'EMAIL:API_KEY' \ -d '{"name":"myredis", "region":"global", "primary_region":"us-east-1", "read_regions":["us-west-1","us-west-2"], "tls": true}' ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier of the created database. - **name** (string) - The name of the database. - **region** (string) - The global region of the database. - **primary_region** (string) - The primary AWS region. - **read_regions** (array of strings) - List of read replica regions. - **tls** (boolean) - TLS status. - **connection_urls** (object) - Object containing connection URLs (e.g., `['redis', 'rediss']`). #### Response Example ```json { "id": "some-database-id", "name": "myredis", "region": "global", "primary_region": "us-east-1", "read_regions": [ "us-west-1", "us-west-2" ], "tls": true, "connection_urls": { "redis": "redis://...", "rediss": "rediss://..." } } ``` ``` -------------------------------- ### ZCOUNT Command Example in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zcount Demonstrates how to use the ZCOUNT command in Upstash Redis with TypeScript. It first adds elements to a sorted set using ZADD and then uses ZCOUNT to retrieve the number of elements within a specified score range. The example shows filtering by excluding a score and including positive infinity. ```typescript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zcount("key", "(1", "+inf"); console.log(elements); // 1 ``` -------------------------------- ### Example Console Output of URL Shortener Source: https://upstash.com/docs/redis/overall/llms-txt This snippet displays a typical console output after successfully running the `url_shortener.py` script. It shows the generated shortened URL and confirms the successful retrieval of the original URL using the short code. ```APIDOC ## Example Console Output of URL Shortener ### Description This snippet displays a typical console output after successfully running the `url_shortener.py` script. It shows the generated shortened URL and confirms the successful retrieval of the original URL using the short code. ### Console Output ```shell Shortened URL: https://short.url/0lSLFI Original URL: https://example.com/my-very-long-url ``` ``` -------------------------------- ### Python Example: JSON.SET with XX Option Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `xx=true` option with `redis.json.set` to set a JSON value only if the specified path already exists within the key. ```APIDOC ## JSON.SET Command with XX Option (Python) ### Description Sets a JSON value at a specific path within a JSON document, but only if the specified path already exists. ### Method `redis.json().set(key: str, path: str, value: Any, xx: bool = False, nx: bool = False): str ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client # Assuming 'key', 'value', and the JSON structure with an existing path are defined # Set the value at '$.path' only if '$.path' already exists redis.json().set(key, "$.path", value, xx=True) ``` ### Response #### Success Response - **str**: 'OK' if the operation was successful. #### Response Example ```json "OK" ``` ``` -------------------------------- ### Python Example for LTRIM Redis Command Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the LTRIM command with a Python Redis client. It shows pushing elements to a list, trimming it, and then verifying the list's content after trimming. ```APIDOC ## LTRIM Command Example in Python ### Description Trims a list so that only elements with indices between the given start and stop are kept. ### Method ``` redis.ltrim(key, start, stop) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.rpush("mylist", "one", "two", "three") assert redis.ltrim("mylist", 0, 1) == True assert redis.lrange("mylist", 0, -1) == ["one", "two"] ``` ### Response #### Success Response (200) Returns `True` if the trim operation was successful. #### Response Example ```json True ``` ``` -------------------------------- ### Initialize Fastly Compute Project (JavaScript) Source: https://upstash.com/docs/redis/quickstarts/fastlycompute Initializes a new Fastly Compute@Edge project for JavaScript, specifically choosing an empty starter template. This sets up the basic project structure for a Fastly service. ```shell > fastly compute init Creating a new Compute@Edge project. Press ^C at any time to quit. Name: [fastly-upstash] Description: Author: [enes@upstash.com] Language: [1] Rust [2] JavaScript [3] AssemblyScript (beta) [4] Other ('bring your own' Wasm binary) Choose option: [1] 2 Starter kit: [1] Default starter for JavaScript A basic starter kit that demonstrates routing, simple synthetic responses and overriding caching rules. https://github.com/fastly/compute-starter-kit-javascript-default [2] Empty starter for JavaScript An empty application template for the Fastly Compute@Edge environment which simply returns a 200 OK response. https://github.com/fastly/compute-starter-kit-javascript-empty Choose option or paste git URL: [1] 2 ``` -------------------------------- ### Python Example for HPEXPIRE Usage Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `hpexpire` command in a Python application with the `upstash-redis` client, including a preceding `hset` operation for context. ```APIDOC ## HPEXPIRE Command (Python) ### Description Sets a time-to-live (TTL) in milliseconds for a specific field within a hash. ### Method `redis.hpexpire(hash_name: str, field: str, milliseconds: int): List[int] ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client # Assuming 'hash_name', 'field', and 'value' are defined redis.hset(hash_name, field, value) # Set the expiration time for the field to 1000 milliseconds (1 second) expiration_status = redis.hpexpire(hash_name, field, 1000) print(expiration_status) # Expected output: [1] (indicating success) ``` ### Response #### Success Response - **List[int]**: A list containing a single integer: - `1`: If the expiration was successfully set. - `0`: If the field or hash does not exist, or if the field has no associated expiration. #### Response Example ```json [1] ``` ``` -------------------------------- ### Python Example for HPEXPIREAT Usage Source: https://upstash.com/docs/redis/overall/llms-txt This Python example demonstrates how to use the `hpexpireat` command to set an expiration time for a field within a Redis hash. It first sets a value using `hset` and then asserts that `hpexpireat` successfully sets an expiration 1 second in the future. ```APIDOC ## HPEXPIREAT Command Example in Python ### Description Sets an expiration time in milliseconds for a specific field within a Redis hash. ### Method ``` redis.hpexpireat(hash_name, field, timestamp_in_milliseconds) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.hset(hash_name, field, value) assert redis.hpexpireat(hash_name, field, int(time.time() * 1000) + 1000) == [1] ``` ### Response #### Success Response (200) A list containing a single element, 1, if the timeout was set. An empty list if the field or the key does not exist. #### Response Example ```json [1] ``` ``` -------------------------------- ### Install @upstash/redis Dependency Source: https://upstash.com/docs/redis/tutorials/using_serverless_framework Adds the @upstash/redis package as a project dependency using npm. This is required to interact with Upstash Redis from the Node.js application. ```json { "dependencies": { "@upstash/redis": "latest" } } ``` -------------------------------- ### Run Application Locally (Shell) Source: https://upstash.com/docs/redis/quickstarts/fly Command to start your Node.js application locally. Ensure the 'fly redis connect' tunnel is active before running this command to allow your application to connect to Redis through the established tunnel. ```shell npm start ``` -------------------------------- ### MGET Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Get the values of all the given keys. ```APIDOC ## MGET Command ### Description Retrieves the values associated with multiple keys from Redis. ### Method POST (Implied by `redis.mget`) ### Endpoint `/redis/commands ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "command": "mget", "keys": ["key1", "key2", "key3"] } ``` ### Request Example ```typescript // Assuming 'redis' is a configured Redis client instance const values = await redis.mget("key1", "key2", "key3"); ``` ### Response #### Success Response (200) - **Array**: An array containing the values of the requested keys. If a key does not exist, its corresponding value will be `null`. #### Response Example ```json ["value1", null, "value3"] ``` ``` -------------------------------- ### Python MSETNX Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the MSETNX command with the Upstash Redis Python client. This command sets multiple key-value pairs atomically; if any key already exists, no keys are set. ```python redis.msetnx({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" } }) ``` -------------------------------- ### Python Example: Using SDIFF with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the SDIFF command in Python with the Upstash Redis client. It demonstrates adding elements to two sets and then asserting the correct difference between them. ```APIDOC ## SDIFF Command Example in Python ### Description Returns the difference between multiple sets. The resulting set contains elements that are in the first set but not in any of the other sets. ### Method ``` redis.sdiff(set1, set2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sdiff("set1", "set2") == {"a", "b"} ``` ### Response #### Success Response (200) A set containing the difference between the specified sets. #### Response Example ```json { "a", "b" } ``` ``` -------------------------------- ### TypeScript Example for SADD Command Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the SADD command with the Upstash Redis client in TypeScript, showing the expected return values for different scenarios. ```APIDOC ## SADD Command Example in TypeScript ### Description Adds one or more members to a set. If members are already present, they are ignored. ### Method ```typescript await redis.sadd(key, member1, member2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Adds 'a', 'b', 'c' to the set, returns 3 (number of new elements added) await redis.sadd("key", "a", "b", "c"); // Adds 'a', 'b' to the set. If they already exist, returns 0 (no new elements added) await redis.sadd("key", "a", "b"); ``` ### Response #### Success Response (200) An integer representing the number of elements that were added to the set. ``` -------------------------------- ### Clear JSON Data with Upstash Redis (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/json/clear Demonstrates how to use the `redis.json.clear` command in Python to clear JSON data. The first example clears the entire JSON document associated with a key. The second example shows how to clear a specific path within the JSON document. ```python redis.json.clear("key") ``` ```python redis.json.clear("key", "$.my.key") ``` -------------------------------- ### HMGET Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hmget Demonstrates how to use the HMGET command in Python to retrieve multiple fields from a hash stored in Upstash Redis. It first sets a hash using HSET and then retrieves specific fields using HMGET. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hmget("myhash", "field1", "field2") == ["Hello", "World"] ``` -------------------------------- ### Initialize Fixed Window Ratelimit with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting up a fixed window rate limiter using the `upstash_ratelimit` library with Upstash Redis. ```APIDOC ## Initialize Fixed Window Ratelimit with Upstash Redis ### Description Demonstrates how to set up a fixed window ratelimiter using the `upstash_ratelimit` library, connected to an Upstash Redis instance. It configures a limit of 10 requests per 10-second window. ### Method POST (or equivalent for Ratelimit check) ### Endpoint `/ratelimit/check` (Conceptual endpoint for rate limit check) ### Parameters #### Request Body - **identifier** (string) - Required - A unique identifier for the entity being rate limited (e.g., user ID, IP address). ### Request Example ```python from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # Example usage: # success, remaining_time = ratelimit.take("user_id_123") ``` ### Response #### Success Response (200) - **allowed** (boolean) - Indicates if the request is allowed. - **remaining** (number) - The number of requests remaining within the current window. #### Response Example ```json { "allowed": true, "remaining": 9 } ``` ``` -------------------------------- ### Get List Length with LLEN (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/llen This snippet demonstrates how to use the LLEN command in Upstash Redis to retrieve the number of elements in a list. It first pushes elements into a list using RPUSH and then calls LLEN to get the list's length. The result is then logged to the console. ```typescript await redis.rpush("key", "a", "b", "c"); const length = await redis.llen("key"); console.log(length); // 3 ``` -------------------------------- ### Flush All Keys in Upstash Redis (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/server/flushall Demonstrates how to use the FLUSHALL command in Upstash Redis using Python. It includes examples for both synchronous and asynchronous deletion of all keys. The ASYNC option allows the operation to run in the background, preventing blocking. ```python redis.flushall() ``` ```python redis.flushall(flush_type="ASYNC") ``` -------------------------------- ### Configure Google Cloud Project and Enable Services (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Configures the Google Cloud SDK to set the active project and enable necessary services for Google Cloud Run. It specifically enables the Cloud Run API (`run.googleapis.com`) and the Cloud Build API (`cloudbuild.googleapis.com`). ```bash gcloud config set project cloud-run-sessions gcloud services enable run.googleapis.com gcloud services enable cloudbuild.googleapis.com ``` -------------------------------- ### Get Set Cardinality with SCARD (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/set/scard This snippet demonstrates how to use the SCARD command in TypeScript to retrieve the number of members in a Redis set. It first adds members to a set using SADD and then calls SCARD to get the cardinality. The result is logged to the console. ```typescript await redis.sadd("key", "a", "b", "c"); const cardinality = await redis.scard("key"); console.log(cardinality); // 3 ``` -------------------------------- ### Configure Environment Variables for Upstash Redis Source: https://upstash.com/docs/redis/tutorials/python_realtime_chat Sets up environment variables for connecting to an Upstash Redis instance. These variables include the host, port, and password, which are essential for establishing a secure connection to the Redis database. ```bash UPSTASH_REDIS_HOST=your_upstash_redis_host UPSTASH_REDIS_PORT=your_upstash_redis_port UPSTASH_REDIS_PASSWORD=your_upstash_redis_password ``` -------------------------------- ### HTML for Home Page with Weather Input Source: https://upstash.com/docs/redis/quickstarts/elixir This HTML code defines the structure for the home page of the Redix demo application. It includes a form for user input (location) and displays weather information. The content dynamically changes based on user input and fetched weather data. ```html <.flash_group flash={@flash} />

Redix Demo

<%= if @text do %> <%= @text %> <% end %> <%= if @weather do %>
<%= if @location do %> Location: <%= @location %> <% end %>

Weather: <%= @weather %> °C

<% end %>
``` -------------------------------- ### GETDEL Command Source: https://upstash.com/docs/redis/overall/llms-txt Get the value of a key and delete the key. ```APIDOC ## GETDEL Command ### Description Retrieves the value of a key and then deletes the key. ### Method ``` GETDEL key ``` ### Endpoint N/A (Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```Redis GETDEL mykey ``` ### Response #### Success Response (200) The value of the deleted key, or nil if the key did not exist. ``` -------------------------------- ### Trim JSON Array with TypeScript (Upstash Redis) Source: https://upstash.com/docs/redis/sdks/ts/commands/json/arrtrim Demonstrates how to use the JSON.ARRTRIM command in Upstash Redis with TypeScript. This command trims a JSON array to include only elements within a specified start and stop index. It requires the key of the JSON entry, the path to the array, and the start and stop indices. ```typescript const length = await redis.json.arrtrim("key", "$.path.to.array", 2, 10); ``` -------------------------------- ### Redis BITPOS Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed documentation for the Redis BITPOS command, including its arguments (key, bit, start, end), their types, requirements, and the structure of the integer response. ```APIDOC ## BITPOS Command ### Description Find the position of the first set or clear bit (bit with a value of 1 or 0) in a Redis string key. ### Method N/A (Command Reference) ### Endpoint N/A (Command Reference) ### Parameters #### Command Arguments - **key** (string) - Required - The key to search in. - **bit** (0 | 1) - Required - The bit to search for (0 or 1). - **start** (number) - Optional - The index to start searching at. - **end** (number) - Optional - The index to stop searching at. ### Request Example N/A (Command Reference) ### Response #### Success Response - **result** (integer) - The index of the first occurrence of the bit in the string. ``` -------------------------------- ### Test API Endpoints with Curl Commands Source: https://upstash.com/docs/redis/tutorials/laravel_caching Provides example `curl` commands to interact with the Todo API endpoints. These commands demonstrate how to fetch, create, update, and delete todo items, allowing for testing of the implemented caching logic. ```shell # Get all todos curl http://todo-cache.test/api/todos # Get a specific todo curl http://todo-cache.test/api/todos/1 # Create a new todo curl -X POST http://todo-cache.test/api/todos \ -H "Content-Type: application/json" \ -d '{"title":"New Todo"}' # Update a todo curl -X PUT http://todo-cache.test/api/todos/1 \ -H "Content-Type: application/json" \ -d '{"title":"Updated Todo"}' # Delete a todo curl -X DELETE http://todo-cache.test/api/todos/1 ``` -------------------------------- ### Python Example for HPERSIST Usage Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of `redis.hset`, `redis.hpexpire`, and `redis.hpersist` functions in Python, asserting the expected outcome of removing expiration. ```APIDOC ## Python Example for HPERSIST Usage ### Description Demonstrates the usage of `redis.hset`, `redis.hpexpire`, and `redis.hpersist` functions in Python, asserting the expected outcome of removing expiration. ### Language Python ### Code ```python redis.hset(hash_name, field, value) redis.hpexpire(hash_name, field, 1000) assert redis.hpersist(hash_name, field) == [1] ``` ``` -------------------------------- ### Run Python Script Source: https://upstash.com/docs/redis/overall/llms-txt This snippet provides the command-line instruction to execute the main Python script associated with the project. Ensure Python is installed and the script file 'your_script_name.py' is accessible in the current directory. ```APIDOC ## Run Python Script ### Description Provides the command-line instruction to execute the main Python script. ### Command ```bash python your_script_name.py ``` ``` -------------------------------- ### Implement Feature Flags in Next.js with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to implement feature flags in a Next.js application using Upstash Redis. This involves checking the status of a feature flag stored in Redis to dynamically toggle features. The example includes a function to check feature status and a usage example within a component. ```javascript // Example feature flag check async function isFeatureEnabled(featureName) { const enabled = await redis.get(`feature:${featureName}`); return enabled === 'true'; } // Usage in a component if (await isFeatureEnabled('new_dashboard')) { // Show new dashboard } else { // Show old dashboard } ``` -------------------------------- ### Python EVAL Command Example (Upstash Redis) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates evaluating a Lua script in Python to retrieve a key's value from Upstash Redis. ```python script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ``` -------------------------------- ### GETRANGE Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the GETRANGE Redis command, outlining its required arguments (key, start, end indices) and the expected string response. ```APIDOC ## GETRANGE ### Description Return a substring of value at the specified key. ### Method GETRANGE ### Endpoint GETRANGE ### Parameters #### Path Parameters - **key** (str) - Required - The key to get. - **start** (int) - Required - The start index of the substring. - **end** (int) - Required - The end index of the substring. ### Response #### Success Response (200) - **response** (str) - Required - The substring. ### Response Example ```json { "response": "substring" } ``` ``` -------------------------------- ### TypeScript Sorted Set Operations Example (ZADD, ZRANK) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates adding members to a sorted set using `redis.zadd` and then attempting to retrieve a value using `redis.zrank`. Note: The example's output comment `// 2` is inconsistent with `zrank`'s typical return value, which is a member's rank, not the set's cardinality. This code snippet demonstrates basic sorted set manipulation. ```TypeScript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" } ); const elements = await redis.zrank("key"); console.log(elements); // 2 ``` -------------------------------- ### LTRIM Command Source: https://upstash.com/docs/redis/sdks/py/commands/list/ltrim Trims a list stored at the specified key so that it contains only the specified range of elements. An offset of 0 speaks to the first element of the list, a positive offset speaks to the element at that position, and a negative offset speaks to the element at that position relative to the end of the list. If the start offset is larger than the end of the list, or if the start offset is negative and larger than the length of the list, the empty list is returned. ```APIDOC ## POST /ltrim ### Description Trims a list stored at the specified key so that it contains only the specified range of elements. Elements outside the range are removed. ### Method POST ### Endpoint /ltrim ### Parameters #### Request Body - **key** (str) - Required - The key of the list. - **start** (int) - Required - The index of the first element to keep. - **stop** (int) - Required - The index of the first element to keep. ### Request Example ```json { "key": "mylist", "start": 0, "stop": 1 } ``` ### Response #### Success Response (200) - **result** (bool) - Returns `True` if the list was trimmed, `False` otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### JSON.SET Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the basic usage of the `redis.json.set` method to set a JSON value at a specified path within a given key. ```APIDOC ## JSON.SET ### Description Sets a JSON value at a specified path within a key. ### Method `JSON.SET` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```python redis.json.set(key, "$.path", value) ``` ### Response #### Success Response (200) - status (string) - OK #### Response Example ```json "OK" ``` ``` -------------------------------- ### Access Koyeb Runtime Logs via CLI Source: https://upstash.com/docs/redis/quickstarts/koyeb Streams the runtime logs of a running Koyeb application. This command is essential for debugging issues that occur after the application has been deployed and started. ```bash koyeb service logs example-koyeb-upstash/example-koyeb-upstash -t runtime ``` -------------------------------- ### Python Example: JSON.SET with NX Option Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `nx=true` option with `redis.json.set` to set a JSON value only if the specified path does not already exist within the key. ```APIDOC ## Python JSON.SET Example with NX Option ### Description This example demonstrates using the `nx=true` option with the `redis.json.set` command to conditionally set a JSON value only if the specified path does not already exist. ### Method `JSON.SET` ### Arguments #### Path Parameters - **key** (str) - Required - The key of the JSON document. - **path** (str) - Required - The JSON path to set the value. - **value** (any) - Required - The JSON value to set. - **nx** (bool) - Optional - If true, only set the key if the path does not already exist. ### Request Example ```python value = ... # Define the value to set redis.json.set(key, "$.path", value, nx=True) ``` ``` -------------------------------- ### TypeScript: SDIFFSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `SDIFFSTORE` command in TypeScript with Upstash Redis. The example covers adding members to two sets, calculating the difference between them, and storing the result in a destination set. ```typescript await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sdiff("dest", "set1", "set2"); console.log(diff); // ["a", "b"] ``` -------------------------------- ### LPUSH Command Usage Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the LPUSH command with a Redis client in Python to add multiple elements to the head of a list, and then verifies the list's content and order using LRANGE. ```APIDOC ## LPUSH Command Usage Example in Python ### Description Adds elements to the head of a list and verifies the list's content and order. ### Method ``` redis.lpush(key, element1, element2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ``` ### Response #### Success Response (200) Integer representing the number of elements added. #### Response Example ```json 3 ``` ``` -------------------------------- ### Get JSON String Length with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/json/strlen This snippet demonstrates how to use the `redis.json.strlen` command in TypeScript to get the length of a JSON string. It requires the Upstash Redis client and specifies the key and path to the string within the JSON document. The function returns an array of integer replies. ```typescript await redis.json.strlen("key", "$.path.to.str", "a"); ``` -------------------------------- ### PUBLISH Source: https://upstash.com/docs/redis/sdks/ts/commands/pubsub/publish Publish a message to a specified channel and get the count of clients that received it. ```APIDOC ## POST /publish ### Description Publish a message to a channel. This endpoint allows you to send a message to a specific channel and returns the number of clients that successfully received the message. ### Method POST ### Endpoint /publish ### Parameters #### Request Body - **channel** (string) - Required - The channel to publish to. - **message** (TMessage) - Required - The message to publish. ### Request Example ```typescript const listeners = await redis.publish("my-channel", "my-message"); ``` ### Response #### Success Response (200) - **listeners** (integer) - Required - The number of clients who received the message. #### Response Example ```json { "listeners": 1 } ``` ``` -------------------------------- ### Python Example for JSON.NUMINCRBY Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `redis.json.numincrby` method in Python to increment a numeric value at a specified path within a JSON document. ```APIDOC ## JSON.NUMINCRBY (Python SDK) ### Description Increments a numeric value at a specified path within a JSON document stored in Redis. ### Method SDK Method Call ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments (for `redis.json.numincrby`) - **key** (string) - Required - The key of the JSON document. - **path** (string) - Required - The JSONPath expression to the numeric value. - **increment** (integer | float) - Required - The value to increment by. ### Request Example (Python) ```python import redis r = redis.Redis(url="YOUR_REDIS_URL") newValue = r.json().numincrby('my-json-key', '$.path.to.numeric.value', 2) print(f"New value: {newValue}") ``` ### Response #### Success Response (200) - **newValue** (integer | float) - The updated numeric value at the specified path. #### Response Example ```python # Assuming the original value was 5, and increment is 2 # New value: 7 ``` ``` -------------------------------- ### XRANGE Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the XRANGE command, outlining its parameters (key, start, end, count) with their types and descriptions, and specifying the structure of the returned stream entries. ```APIDOC ## XRANGE Command API Reference ### Description Returns stream entries matching a given range of IDs. ### Method ``` XRANGE key start end [COUNT count] ``` ### Endpoint N/A (Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```APIDOC XRANGE mystream - + COUNT 10 ``` ### Response #### Success Response (200) A map of stream entries, where each entry is keyed by its stream ID and contains a map of field-value pairs. #### Response Example ```json { "1678882602647-0": { "sensor-id": "1", "temperature": "25.5" }, "1678882603000-0": { "sensor-id": "2", "temperature": "26.1" } } ``` ``` -------------------------------- ### Serverless JavaScript Redis Client Initialization Source: https://upstash.com/docs/redis/overall/llms-txt Provides a JavaScript example for a serverless function handler demonstrating how to initialize a Redis client, perform operations, and ensure the connection is properly closed to manage concurrent connections effectively. ```APIDOC ## Serverless Redis Handler (JavaScript) ### Description Example of a serverless function handler for Redis operations in JavaScript, including client initialization and connection closing. ### Method exports.handler ### Parameters #### Environment Variables - **REDIS_URL** (string) - Required - The URL for the Redis connection. ### Example ```javascript exports.handler = async (event) => { const client = new Redis(process.env.REDIS_URL); /* do stuff with redis */ await client.quit(); /* do other stuff */ return { response: "response" }; }; ``` ``` -------------------------------- ### Run Celery Worker Source: https://upstash.com/docs/redis/integrations/celery Starts a Celery worker process. This command tells Celery to monitor the specified application ('tasks') for new tasks and execute them with informational logging. ```bash celery -A tasks worker --loglevel=info ``` -------------------------------- ### Basic XAUTOCLAIM in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xautoclaim Performs a basic XAUTOCLAIM operation to transfer pending messages. It requires the stream key, consumer group name, the new consumer name, the minimum idle time for messages to be claimed, and the starting stream entry ID. The result includes the next start ID for pagination, claimed messages with their data, and any deleted message IDs. ```typescript const result = await redis.xautoclaim( "mystream", "mygroup", "consumer1", 60000, "0-0" ); ``` -------------------------------- ### Initialize Upstash Redis in Node.js/Browser Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing the Upstash Redis client in Node.js or browser environments. It shows how to configure the client using explicit URL and token, or by loading directly from environment variables using `Redis.fromEnv()`, which is suitable for serverless platforms. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` -------------------------------- ### Upstash Redis ZDIFF Command with Scores Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zdiff Illustrates the usage of the ZDIFF command in Upstash Redis when the 'withscores' option is enabled. This returns the differing elements along with their scores. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zdiff(["key1", "key2"], withscores=True) assert result == [("a", 1), ("b", 2)] ``` -------------------------------- ### XPENDING Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xpending Returns information about pending messages in a stream consumer group. It can be used to get a summary or detailed pending message information based on provided range arguments. ```APIDOC ## XPENDING ### Description Returns information about pending messages in a stream consumer group. It can be used to get a summary or detailed pending message information based on provided range arguments. ### Method GET (or relevant method for Redis commands) ### Endpoint /stream/xpending ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. - **group** (str) - Required - The consumer group name. #### Query Parameters - **start** (str) - Optional - The minimum pending ID to return (use with end and count). - **end** (str) - Optional - The maximum pending ID to return (use with start and count). - **count** (int) - Optional - The maximum number of pending messages to return. - **consumer** (str) - Optional - Filter results by a specific consumer. - **idle** (int) - Optional - Filter by minimum idle time in milliseconds. ### Request Example ```py # Summary theme={"system"} redis.xpending("mystream", "mygroup") # Detailed with range theme={"system"} redis.xpending("mystream", "mygroup", start="-", end="+", count=10) # Specific consumer with idle filter theme={"system"} redis.xpending("mystream", "mygroup", start="-", end="+", count=5, consumer="consumer1", idle=10000) ``` ### Response #### Success Response (200) - **Any** (type) - When called without range arguments, returns a summary with total count and range info. When called with range arguments, returns detailed pending message information. #### Response Example ```py # Summary response example theme={"system"} [ 2, # total pending count "1638360173533-0", # smallest pending ID "1638360173533-1", # greatest pending ID [["consumer1", "2"]] # consumers and their pending counts ] ``` ``` -------------------------------- ### Initialize Upstash Redis in Deno Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize an Upstash Redis client in Deno environments, supporting direct configuration or environment variable loading. ```APIDOC ## Initialize Upstash Redis in Deno ### Description Initializes an Upstash Redis client in Deno environments, including Deno Deploy and Netlify Edge. ### Usage **Explicit Configuration:** ```ts import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: "", token: "", }) ``` **From Environment Variables:** ```ts import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = Redis.fromEnv(); ``` ``` -------------------------------- ### GET /functions/stats Source: https://upstash.com/docs/redis/sdks/ts/commands/functions/stats Fetches statistics about the function running engines, including library and function counts for each engine. ```APIDOC ## GET /functions/stats ### Description Retrieves statistics about the function running engines, including the number of libraries and functions for each engine. ### Method GET ### Endpoint /functions/stats ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **engines** (Object) - Stats about the engines and functions. Currently, `LUA` is the only supported engine. - **LUA** (Object) - Statistics specific to the LUA engine. - **librariesCount** (number) - The number of libraries available for the LUA engine. - **functionsCount** (number) - The number of functions available for the LUA engine. #### Response Example ```json { "engines": { "LUA": { "librariesCount": 3, "functionsCount": 15 } } } ``` ``` -------------------------------- ### Upstash Redis Environment Variables Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Example of environment variables required to connect to an Upstash Redis database. These credentials should be obtained from the Upstash Console or CLI and stored in a `.env` file. ```APIDOC ## Environment Variables Configuration ### Description Specifies the environment variables needed to establish a connection with an Upstash Redis database. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Environment Variables - **UPSTASH_REDIS_REST_URL** (string) - Required - The URL for your Upstash Redis REST endpoint. - **UPSTASH_REDIS_REST_TOKEN** (string) - Required - The access token for your Upstash Redis database. ### Request Example ```plaintext UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ### Response N/A (Configuration) ### Note These credentials can be obtained from the Upstash Console or CLI and should typically be stored securely in a `.env` file. ``` -------------------------------- ### Populate Upstash Redis with Coin Data Source: https://upstash.com/docs/redis/tutorials/coin_price_list This command demonstrates how to populate an Upstash Redis database with initial coin data, including name, price, and image URL, using the RPUSH command. This data serves as the source for the coin price list application. ```shell rpush coins '{ "name" : "Bitcoin", "price": 56819, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png"}' '{ "name" : "Ethereum", "price": 2130, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png"}' '{ "name" : "Cardano", "price": 1.2, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/2010.png"}' '{ "name" : "Polkadot", "price": 35.96, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/6636.png"}' '{ "name" : "Stellar", "price": 0.506, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/512.png"} ``` -------------------------------- ### Python Examples for HRANDFIELD Command Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `hrandfield` method with the Upstash Redis Python client to retrieve single, multiple, or value-paired random fields from a hash. ```APIDOC ## Python HRANDFIELD Command Examples ### Description This section demonstrates retrieving random fields from a hash using the `hrandfield` method in Python. ### Examples 1. **Get a single random field:** ```python redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) assert redis.hrandfield("myhash") in ["field1", "field2"] ``` 2. **Get multiple random fields:** ```python redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) assert redis.hrandfield("myhash", count=2) in [ ["field1", "field2"], ["field2", "field1"] ] ``` 3. **Get a single random field with its value:** ```python redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) assert redis.hrandfield("myhash", count=1, withvalues=True) in [ {"field1": "Hello"}, {"field2": "World"} ] ``` ``` -------------------------------- ### TypeScript Example for JSON.OBJLEN Usage Source: https://upstash.com/docs/redis/overall/llms-txt A practical TypeScript code snippet demonstrating how to call the `json.objlen` method using the Upstash Redis client to retrieve the number of keys in a JSON object. ```APIDOC ## TypeScript JSON.OBJLEN Example ### Description Retrieves the number of keys in a JSON object at a specified path within a Redis key using the `json.objlen` method. ### Method `POST` ### Endpoint `/json/objlen` ### Parameters #### Request Body - **key** (string) - Required - The key of the JSON document. - **path** (string) - Optional - The JSON path to the object. Defaults to root if not provided. ### Request Example ```json { "key": "key", "path": "$.path" } ``` ### Response #### Success Response (200) - **(integer)** - The number of fields in the JSON object. #### Response Example ```json 5 ``` ### Code Example ```ts const lengths = await redis.json.objlen("key", "$.path"); ``` ``` -------------------------------- ### TypeScript Example for ZMSCORE and ZADD Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates adding members to a sorted set using `redis.zadd` and then retrieving their scores using `redis.zmscore` from an Upstash Redis instance. ```APIDOC ## ZADD and ZMSCORE Commands (TypeScript) ### Description Adds members with their scores to a sorted set using `ZADD` and retrieves the scores of specified members using `ZMSCORE`. ### Method `redis.zadd(key: string, ...members: { score: number; member: string }[]): Promise `redis.zmscore(key: string, members: string[]): Promise<(number | null)[]> ### Endpoint N/A (SDK Methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // Add members to a sorted set await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, { score: 4, member: "m4" }, ); // Retrieve scores of specific members const scores = await redis.zmscore("key", ["m2", "m4"]); console.log(scores); // [2, 4] ``` ### Response #### Success Response (ZADD) - **number**: The number of elements added to the sorted set. #### Success Response (ZMSCORE) - **(number | null)[]**: An array of scores corresponding to the requested members. `null` if a member is not found. #### Response Example (ZMSCORE) ```json [2, 4] ``` ``` -------------------------------- ### Redis XCLAIM: Basic Message Claiming (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xclaim Demonstrates how to use the XCLAIM command in TypeScript to claim messages from a Redis stream. This example shows the basic usage without any optional parameters. ```typescript const result = await redis.xclaim( "mystream", "mygroup", "consumer1", 60000, ["1638360173533-0", "1638360173533-1"] ); ``` -------------------------------- ### TypeScript Example for JSON.ARRLEN Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript code snippet demonstrating how to use the `json.arrlen` method with the Upstash Redis client to retrieve the length of a JSON array. ```APIDOC ## TypeScript Example for JSON.ARRLEN ### Description A TypeScript code snippet demonstrating how to use the `json.arrlen` method with the Upstash Redis client to retrieve the length of a JSON array. ### Language TypeScript ### Code ```ts const length = await redis.json.arrlen("key", "$.path.to.array"); ``` ``` -------------------------------- ### Example ZINCRBY Usage in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZINCRBY command with an Upstash Redis client in Python, including adding initial members to a sorted set and asserting the incremented score. ```APIDOC ## Python ZINCRBY Example ### Description This example demonstrates how to use the `zincrby` command in Python to increment the score of a member in a sorted set. ### Method `ZINCRBY` ### Arguments #### Path Parameters - **key** (str) - Required - The key of the sorted set. - **increment** (float | int) - Required - The amount to increment the score by. - **member** (str) - Required - The member whose score is to be incremented. ### Request Example ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zincrby("myset", 2, "one") == 3 ``` ### Response #### Success Response (200) - **(float | int)** - The new score of the member. ``` -------------------------------- ### ZINTER: Aggregation with Scores (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zunion Shows how to perform a ZINTER operation with aggregation and include scores in the result. This example uses the 'SUM' aggregation on two sets and returns the combined scores for common elements. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` -------------------------------- ### SCARD - Get Set Cardinality Source: https://upstash.com/docs/redis/sdks/ts/commands/set/scard The SCARD command returns the number of elements (cardinality) of a set stored at the specified key. ```APIDOC ## POST /v2/redis/scard ### Description Returns the number of members in a set. ### Method POST ### Endpoint /v2/redis/scard ### Parameters #### Query Parameters - **key** (string) - Required - The key of the set. ### Request Body This endpoint does not require a request body. ### Response #### Success Response (200) - **value** (number) - How many members are in the set. #### Response Example ```json { "value": 3 } ``` ``` -------------------------------- ### Deploy Application with Koyeb CLI Source: https://upstash.com/docs/redis/overall/llms-txt Deploys an application to Koyeb using the CLI, configuring the Git repository, branch, ports, routes, and essential environment variables for Upstash Redis integration. ```APIDOC ## Deploy Application to Koyeb ### Description Deploys an application to Koyeb using the CLI, configuring necessary settings for Upstash Redis integration. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters #### CLI Arguments - **`example-koyeb-upstash`** (string) - The name of the Koyeb application. - **`--git`** (string) - The Git repository URL (e.g., `github.com//`). - **`--git-branch`** (string) - The Git branch to deploy (e.g., `main`). - **`--ports`** (string) - Defines the ports to expose (e.g., `3000:http`). - **`--routes`** (string) - Defines the routing rules (e.g., `/:3000`). - **`--env`** (string) - Environment variables to set (e.g., `PORT=3000`, `UPSTASH_REDIS_REST_URL=...`, `UPSTASH_REDIS_REST_TOKEN=...`). ### Request Example ```bash koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ``` ### Response #### Success Response - Output from the Koyeb CLI indicating successful deployment. #### Response Example (CLI output will vary) ``` -------------------------------- ### HP TTL Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to set a hash field, apply a millisecond expiration to it, and then retrieve its remaining TTL using the `hpttl` command in Python. ```APIDOC ## HP TTL (Hpexpire and Hpttl) ### Description Sets a field in a hash with a millisecond expiration and retrieves its remaining TTL. ### Method `HSET`, `HPEXPIRE`, `HPTTL` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```python redis.hset(hash_name, field, value) redis.hpexpire(hash_name, field, 1000) assert redis.hpttl(hash_name, field) == [950] # Example assertion ``` ### Response #### Success Response (200) - ttl (integer) - The remaining time-to-live in milliseconds. ``` -------------------------------- ### Get Histogram API Source: https://upstash.com/docs/redis/tutorials/histogram This endpoint retrieves the histogram data for a specified test name. It requires the test name as a query parameter. ```APIDOC ## GET /get ### Description Retrieves the histogram data for a given test name. ### Method GET ### Endpoint https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get ### Parameters #### Path Parameters None #### Query Parameters - **name** (string) - Required - The name of the test to retrieve histogram data for. #### Request Body None ### Request Example ``` curl https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get?name=perf-test-1 ``` ### Response #### Success Response (200) - **histogram** (object) - An object representing the histogram data. #### Response Example ```json { "histogram": { "90": 1, "80": 1, "34": 1, "97": 1, "93": 1, "45": 1, "49": 1, "57": 1, "99": 1, "12": 1 } } ``` ``` -------------------------------- ### SCARD - Get Set Size Source: https://upstash.com/docs/redis/sdks/py/commands/set/scard The SCARD command returns the number of elements (members) in a set stored at the specified key. ```APIDOC ## SCARD ### Description Return how many members are in a set. ### Method GET ### Endpoint /SCARD ### Parameters #### Query Parameters - **key** (str) - Required - The key of the set. ### Request Example ``` GET /SCARD?key=my_set ``` ### Response #### Success Response (200) - **count** (int) - Required - How many members are in the set. #### Response Example ```json { "count": 3 } ``` ``` -------------------------------- ### Token Bucket Rate Limiter Usage (Python) Source: https://upstash.com/docs/redis/sdks/ratelimit-py/algorithms Provides a Python code example for initializing and using the Token Bucket rate limiter with Upstash Redis. It depends on `upstash_ratelimit` and `upstash_redis` libraries and is configured with maximum tokens, refill rate, and interval. ```python from upstash_ratelimit import Ratelimit, TokenBucket from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=TokenBucket(max_tokens=10, refill_rate=5, interval=10), ) ``` -------------------------------- ### Redis BITOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documentation for the Redis BITOP command, detailing its operations (AND, OR, XOR, NOT), required arguments (destkey, keys), and the integer response indicating the size of the stored string. ```APIDOC BITOP Command: Description: Perform bitwise operations on multiple keys and store the result in a destination key. Arguments: operation: AND | OR | XOR | NOT (required) Description: Specifies the type of bitwise operation to perform. destkey: str (required) Description: The key to store the result of the operation in. keys: *List[str] (required) Description: One or more keys to perform the operation on. Response: type: int (required) Description: The size of the string stored in the destination key. ``` -------------------------------- ### LRANGE Command API Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the Redis LRANGE command, outlining its required parameters (key, start, end indices) and the expected array response. ```APIDOC ## LRANGE Command ### Description Returns the specified elements of the list stored at key. ### Method POST (Implied by command format) ### Endpoint /redis/v1/command (Implied by context) ### Arguments #### Request Body - **key** (string) - Required - The key of the list. - **start** (integer) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (integer) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Request Example ```json { "command": "LRANGE", "key": "my_list_key", "start": 0, "end": -1 } ``` ### Response #### Success Response (200) - **result** (TValue[]) - The list of elements in the specified range. ### Response Example ```json { "result": ["element1", "element2", "element3"] } ``` ``` -------------------------------- ### XRANGE Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrange Fetches stream entries from a Redis stream that match a given range of IDs. You can specify the start and end IDs, and optionally limit the number of entries returned. ```APIDOC ## GET /stream/{key} ### Description Returns stream entries matching a given range of IDs. ### Method GET ### Endpoint /stream/{key} ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. #### Query Parameters - **start** (str) - Optional - The stream entry ID to start from. Use "-" for the first available ID. Defaults to "-". - **end** (str) - Optional - The stream entry ID to end at. Use "+" for the last available ID. Defaults to "+". - **count** (int) - Optional - The maximum number of entries to return. ### Response #### Success Response (200) - **Response** (List[Tuple[str, List[str]]]) - A list of stream entries, where each entry is a tuple containing the stream ID and its associated fields and values. #### Response Example ```json { "1548149259438-0": { "field1": "value1", "field2": "value2" }, "1548149259438-1": { "field1": "value3", "field2": "value4" } } ``` ``` -------------------------------- ### Build Container Image with gcloud Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions Command to build a Docker container image and tag it for Google Container Registry. This is a prerequisite for deploying to Cloud Run. ```bash gcloud builds submit --tag gcr.io/cloud-run-sessions/main ``` -------------------------------- ### Example Console Output of Python URL Shortener Source: https://upstash.com/docs/redis/overall/llms-txt Displays typical console output after running a Python URL shortener script. It shows the generated shortened URL and confirms successful retrieval of the original URL using the short code. ```shell Shortened URL: https://short.url/0lSLFI Original URL: https://example.com/my-very-long-url ``` -------------------------------- ### Initialize Redis Database (JavaScript) Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Initializes the Redis database with country names and their prefixes. It iterates through a list of countries, generates all possible prefixes for each country name, and adds them to a Redis Sorted set named 'terms' with a score of 0. ```javascript require('dotenv').config() var Redis = require("ioredis"); var countries = [ {"name": "Afghanistan", "code": "AF"}, {"name": "Åland Islands", "code": "AX"}, {"name": "Albania", "code": "AL"}, {"name": "Algeria", "code": "DZ"}, ... ] var client = new Redis(process.env.REDIS_URL); for (const country of countries) { let term = country.name.toUpperCase(); let terms = []; for (let i = 1; i < term.length; i++) { terms.push(0); terms.push(term.substring(0, i)); } terms.push(0); terms.push(term + "*"); (async () => { await client.zadd("terms", ...terms) })(); } ``` -------------------------------- ### GET / - Leaderboard API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieve leaderboard data and measure request latency from a local Cloudflare Worker endpoint. ```APIDOC ## GET / ### Description Send a GET request to a local Cloudflare Worker endpoint to retrieve the current leaderboard and measure the total request latency. ### Method GET ### Endpoint `http://127.0.0.1:8787` ### Parameters #### Query Parameters None ### Request Example ```bash curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ``` ### Response #### Success Response (200) - **leaderboard_data** (Object | Array) - The retrieved leaderboard data. - **latency** (string) - The measured request latency (e.g., '0.123s'). #### Response Example ```json { "leaderboard": [ {"user": "user1", "score": 100}, {"user": "user2", "score": 90} ] } Latency: 0.123s ``` ``` -------------------------------- ### Basic Upstash Redis Usage in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/getstarted Demonstrates fundamental operations with the Upstash Redis client in TypeScript, including setting and getting string values, and using sorted sets, lists, hashes, and sets. Requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) await redis.set('key2', 'value2', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ``` -------------------------------- ### Initialize Upstash Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize an Upstash Redis client in Node.js or browser environments using environment variables or explicit configuration. ```APIDOC ## Initialize Upstash Redis Client ### Description Initializes the Upstash Redis client for Node.js and browser environments. ### Usage Configuration can be loaded from explicit URL/token environment variables or directly using `Redis.fromEnv()`. ### Example (Explicit Configuration) ```ts import { Redis } from "@upstash/redis" const redis = new Redis({ url: "", token: "", }) ``` ### Example (From Environment Variables) ```ts import { Redis } from "@upstash/redis" // Loads configuration from UPSTASH_REDIS_URL and UPSTASH_REDIS_TOKEN environment variables const redis = Redis.fromEnv() ``` ``` -------------------------------- ### LRANGE Command Source: https://upstash.com/docs/redis/sdks/py/commands/list/lrange Retrieves a range of elements from a list stored at a specified key. You can define the start and end indices, including negative offsets from the end of the list. ```APIDOC ## GET /lrange ### Description Returns the specified elements of the list stored at key. ### Method GET ### Endpoint /lrange ### Parameters #### Query Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (int) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response #### Success Response (200) - **List[str]** - The list of elements in the specified range. #### Response Example { "example": [ "one", "two" ] } ### Request Example ```py Example theme={"system"} redis.rpush("mylist", "one", "two", "three") assert redis.lrange("mylist", 0, 1) == ["one", "two"] assert redis.lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ``` -------------------------------- ### Redis @ Edge with Cloudflare Workers Source: https://upstash.com/docs/redis/overall/llms-txt Example demonstrating how to use Upstash Redis with Cloudflare Workers for low-latency data access at the edge. ```APIDOC ## POST /edge/redis ### Description Sets and gets data from Upstash Redis using Cloudflare Workers, enabling edge data access. ### Method POST ### Endpoint /edge/redis ### Parameters #### Request Body - **key** (string) - The key to set in Redis. - **value** (string) - The value to set for the key. ### Request Example ```javascript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: env.REDIS_URL, token: env.REDIS_TOKEN, }); export default { async fetch(request, env) { // Example: Setting a key await redis.set('edge_data', 'hello from the edge'); // Example: Getting a key const data = await redis.get('edge_data'); return new Response(data); }, }; ``` ### Response #### Success Response (200) - **data** (string) - The data retrieved from Redis. #### Response Example ``` hello from the edge ``` ``` -------------------------------- ### Redis TYPE Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `upstash-redis` client in TypeScript to set a key with a string value and then retrieve its data type using the `type` command. ```APIDOC ## Redis TYPE Command Example (TypeScript) ### Description Sets a key with a string value and then retrieves its data type using the `type` command. ### Method `redis.type(key)` ### Endpoint N/A (Client-side SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript await redis.set("key", "value"); const t = await redis.type("key"); console.log(t); // "string" ``` ### Response #### Success Response (200) - **type** (string) - The data type of the key (e.g., "string", "hash", "list"). #### Response Example ```json "string" ``` ``` -------------------------------- ### Redis Pipeline Example in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/pipelining/pipeline-transaction Demonstrates how to use the pipeline feature in Upstash Redis with TypeScript. Pipelining allows sending multiple commands in a single HTTP request, but execution is not atomic. It takes a Redis client instance and returns an array of command responses. ```typescript import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.pipeline(); // Now you can chain multiple commands to create your pipeline: p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // Execute the pipeline once you are done building it: // `exec` returns an array where each element represents the response of a command in the pipeline. // You can optionally provide a type like this to get a typed response. const res = await p.exec<[Type1, Type2, Type3]>(); ``` -------------------------------- ### XLEN - Get Stream Length Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xlen The XLEN command returns the number of entries inside a stream. If the stream does not exist, it returns 0. ```APIDOC ## GET /websites/upstash-redis/xlen ### Description Returns the number of entries inside a stream. ### Method GET ### Endpoint /websites/upstash-redis/xlen ### Parameters #### Query Parameters - **key** (str) - Required - The key of the stream. ### Request Example ```http GET /websites/upstash-redis/xlen?key=mystream ``` ### Response #### Success Response (200) - **count** (int) - The number of entries in the stream. Returns 0 if the stream does not exist. #### Response Example ```json { "count": 10 } ``` ``` -------------------------------- ### RPUSH Command API Reference and Usage Source: https://upstash.com/docs/redis/overall/llms-txt Comprehensive API documentation for the RPUSH command, including its required arguments (key, elements), the type of response (list length), and a TypeScript example demonstrating how to use the command with an Upstash Redis client. ```APIDOC ## RPUSH Command ### Description Push an element at the end of the list. ### Method RPUSH ### Endpoint RPUSH ### Parameters #### Path Parameters - **key** (string) - Required - The key of the list. - **elements** (...TValue[]) - Required - One or more elements to push at the end of the list. ### Response #### Success Response (200) - **response** (number) - Required - The length of the list after the push operation. ### Request Example ```json { "key": "myList", "elements": ["a", "b", "c"] } ``` ### Response Example ```json { "response": 3 } ``` ``` -------------------------------- ### Python ZSCORE Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the ZSCORE command in Python. It shows how to add members with scores to a sorted set and then retrieve the score of a specific member. ```python redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zscore("myset", "a") == 1 ``` -------------------------------- ### Next.js Integration Placeholder (Next.js) Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder snippet indicating the integration of Upstash Redis within a Next.js application. This serves as a starting point for more complex integrations. ```nextjs console.log('This is a placeholder for Next.js code.'); ``` -------------------------------- ### Initialize SST for Serverless Deployment Source: https://upstash.com/docs/redis/overall/llms-txt A shell command to initialize the Serverless Stack Toolkit (SST) within a project directory, preparing it for serverless application deployment. ```shell sst init ``` -------------------------------- ### LRANGE Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Defines the LRANGE command, its required parameters (key, start, end indices), and the structure of its response, including type and description for each element. ```APIDOC ## LRANGE Command ### Description Returns the specified elements of the list stored at key. ### Method LRANGE ### Endpoint LRANGE ### Parameters #### Path Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (int) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response #### Success Response (200) - **response** (List[str]) - The list of elements in the specified range. ### Response Example ```json { "response": ["element1", "element2"] } ``` ``` -------------------------------- ### Database Setup: Configure Upstash Redis Environment Variables Source: https://upstash.com/docs/redis/overall/llms-txt Sets the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` as secure secrets using the SST CLI. These secrets will be securely injected into your application at runtime. ```APIDOC ## Configure Upstash Redis Environment Variables ### Description This guide details how to set Upstash Redis REST URL and Token as secure secrets using the SST CLI, ensuring they are securely available to your application at runtime. ### Commands ```shell npx sst secrets set UPSTASH_REDIS_REST_URL npx sst secrets set UPSTASH_REDIS_REST_TOKEN ``` ``` -------------------------------- ### XREAD Command Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xread Reads data from one or multiple streams, starting from the specified IDs. Supports options for limiting the number of messages and reading only new messages. ```APIDOC ## POST /v1/redis/xread ### Description Reads data from one or multiple streams, starting from the specified IDs. Use `$` to read only new messages added after the command is issued. ### Method POST ### Endpoint /v1/redis/xread ### Parameters #### Request Body - **streams** (Dict[str, str]) - Required - A dictionary mapping stream keys to their starting IDs. - **count** (int) - Optional - The maximum number of messages to return per stream. ### Request Example ```json { "streams": {"mystream": "0-0"}, "count": 10 } ``` ### Response #### Success Response (200) - **response** (List[List[Any]]) - Returns a list where each element represents a stream and contains the stream key and a list of messages (ID and field-value pairs). Returns an empty list if no data is available. #### Response Example ```json [ ["mystream", [ ["1638360173533-0", {"field1": "value1", "field2": "value2"}], ["1638360173533-1", {"field1": "value3", "field2": "value4"}] ]] ] ``` ``` -------------------------------- ### Load and Execute Lua Script with Python Source: https://upstash.com/docs/redis/overall/llms-txt This Python example demonstrates how to use the `script_load` method to load a Lua script into Redis and then execute it using `evalsha`, asserting the correct return value. ```APIDOC ## Load and Execute Lua Script with Python ### Description This Python example demonstrates how to use the `script_load` method to load a Lua script into Redis and then execute it using `evalsha`, asserting the correct return value. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```python sha1 = redis.script_load("return 1") assert redis.evalsha(sha1) == 1 ``` ### Response N/A (SDK Example) ``` -------------------------------- ### HMGET Command Example in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/hash/hmget Demonstrates how to use the HMGET command in Upstash Redis to retrieve specific fields from a hash. It first sets multiple fields using HSET and then fetches 'username' and 'name' using HMGET. The result is logged to the console. ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const fields = await redis.hmget("key", "username", "name"); console.log(fields); // { username: "chronark", name: "andreas" } ``` -------------------------------- ### Run Cloudflare Worker Locally Source: https://upstash.com/docs/redis/overall/llms-txt Starts a local development server for the Cloudflare Worker using `npx wrangler dev`, allowing for testing and debugging the worker's functionality before deployment. ```APIDOC ## Run Cloudflare Worker Locally ### Description Starts a local development server for the Cloudflare Worker using `npx wrangler dev`, allowing for testing and debugging the worker's functionality before deployment. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```shell npx wrangler dev ``` ### Response Success Response (200) - A local development server for the Cloudflare Worker is started. ### Response Example ``` { ... local server logs ... } ``` ``` -------------------------------- ### Manage Serverless Redis Connections in JavaScript Source: https://upstash.com/docs/redis/overall/llms-txt Provides a JavaScript example for a serverless function handler demonstrating how to initialize a Redis client, perform operations, and ensure the connection is properly closed to manage concurrent connections effectively. ```javascript exports.handler = async (event) => { const client = new Redis(process.env.REDIS_URL); /* do stuff with redis */ await client.quit(); /* do other stuff */ return { response: "response" }; }; ``` -------------------------------- ### API Documentation for LTRIM Redis Command Source: https://upstash.com/docs/redis/overall/llms-txt Provides detailed API documentation for the LTRIM Redis command. It outlines the required arguments (key, start, stop), their types, and the boolean response that indicates whether the list trimming operation was successful. ```apidoc LTRIM Command: Description: Trim a list to the specified range Arguments: key: Type: str Required: true Description: The key of the list. start: Type: int Required: true Description: The index of the first element to keep. stop: Type: int Required: true Description: The index of the first element to keep. Response: Type: bool Required: true Description: Returns `True` if the list was trimmed, `False` otherwise. ``` -------------------------------- ### LLEN - Get List Length Source: https://upstash.com/docs/redis/sdks/py/commands/list/llen The LLEN command returns the number of elements in the list stored at the specified key. If the key does not exist, it returns 0. ```APIDOC ## GET /llen ### Description Returns the length of the list stored at key. ### Method GET ### Endpoint /llen ### Parameters #### Query Parameters - **key** (str) - Required - The key of the list. ### Request Example ```http GET /llen?key=my_list ``` ### Response #### Success Response (200) - **length** (int) - The length of the list at key. #### Response Example ```json { "length": 3 } ``` ``` -------------------------------- ### Placeholder for Java Serverless API Example Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder indicating where Java code would be integrated for building a serverless API with Upstash Redis, typically deployed on platforms like AWS Lambda. ```java System.out.println("This is a placeholder for Java code."); ``` -------------------------------- ### SRANDMEMBER Usage Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to retrieve multiple random members from a Redis set by specifying the `count` argument with `redis.srandmember()` in Python. ```APIDOC ## SRANDMEMBER Command (Python) ### Description Return one or more random members from a set. ### Method SRANDMEMBER ### Endpoint N/A (SDK usage) ### Parameters #### Arguments - **key** (str) - Required - The key of the set. - **count** (int) - Optional - The number of members to return. If not provided, a single random member is returned. ### Request Example ```python redis.sadd("myset", "one", "two", "three") # Get a single random member single_member = redis.srandmember("myset") # Get multiple random members multiple_members = redis.srandmember("myset", 2) assert multiple_members in ({"one", "two"}, {"one", "three"}, {"two", "three"}) ``` ### Response #### Success Response (200) - **member(s)** (str | List[str]) - A random member if count is not specified, or a list of random members if count is specified. ``` -------------------------------- ### Redis SET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed documentation for the Redis SET command, outlining its required and optional arguments, their types, descriptions, and the expected response. ```APIDOC ## Redis SET Command API Reference ### Description Set a key to hold a string value. ### Method SET ### Endpoint Not applicable (command-line interface or SDK method) ### Parameters #### Arguments - **key** (string) - Required - The key to set. - **value** (TValue) - Required - The value to store. Non-string values are JSON.stringify'd. - **opts** (object) - Optional - Options to modify SET behavior. - **get** (boolean) - Optional - Returns the old value at key, or null if key did not exist, instead of 'OK'. - **ex** (integer) - Optional - Sets an expiration in seconds. - **px** (integer) - Optional - Sets an expiration in milliseconds. - **exat** (integer) - Optional - Sets an expiration at a specific Unix timestamp (seconds). - **pxat** (integer) - Optional - Sets an expiration at a specific Unix timestamp (milliseconds). - **keepTtl** (boolean) - Optional - Preserves the existing TTL if the key already exists. - **nx** (boolean) - Optional - Only sets the key if it does not already exist. - **xx** (boolean) - Optional - Only sets the key if it already exists. ### Response #### Success Response (200) - **Type**: string - **Value**: "OK" (default) or old value (if 'get' option is used) - **Description**: Returns 'OK' on success, or the old value if 'get' option is specified. ``` -------------------------------- ### XGROUP SETID Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xgroup_setid Set the last delivered ID for a consumer group. This command allows you to specify which message ID a consumer group should start processing from. ```APIDOC ## XGROUP SETID ### Description Set the last delivered ID for a consumer group. ### Method POST ### Endpoint /websites/upstash-redis ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (str) - Required - The key of the stream. - **group** (str) - Required - The consumer group name. - **id** (str) - Required - The stream entry ID to set as the last delivered ID. Use '$' for the last entry. - **entries_read** (int) - Optional - Set the number of entries read by the group. ### Request Example ```json { "key": "mystream", "group": "mygroup", "id": "0-0" } ``` ```json { "key": "mystream", "group": "mygroup", "id": "$", "entries_read": 10 } ``` ### Response #### Success Response (200) - **result** (bool) - Returns "OK" if the ID was set successfully. #### Response Example ```json { "result": "OK" } ``` ``` -------------------------------- ### Basic Redis set and get with default encoding Source: https://upstash.com/docs/redis/sdks/ts/troubleshooting Demonstrates setting a string value and retrieving it from Redis using the Upstash client. By default, responses are base64 encoded to prevent deserialization issues. ```typescript await redis.set("key", "value"); const data = await redis.get("key"); console.log(data); // dmFsdWU= ``` -------------------------------- ### SSCAN Command (Redis) Source: https://upstash.com/docs/redis/overall/llms-txt This entry simply lists the SSCAN command, which is used for incrementally iterating over a dataset in Redis. No further description or example is provided. ```redis SSCAN ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Command to change the current directory to the newly created Serverless project folder, 'counter-serverless'. ```APIDOC ## Navigate to Project Directory ### Description Command to change the current directory to the newly created Serverless project folder, 'counter-serverless'. ### Method Shell command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell cd counter-serverless ``` ### Response N/A ``` -------------------------------- ### JSON Response for Null Redis Result Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns a `null` value. ```APIDOC ## JSON Response for Null Result ### Description Example of a JSON response from the Upstash REST API when a Redis command returns a `null` value. ### Response Example ```json { "result": null } ``` ``` -------------------------------- ### Serverless Golang API with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Example of setting up a serverless Golang API that interacts with Upstash Redis. This is particularly useful for AWS Lambda deployments, showcasing efficient Go application development. ```Go package main import "fmt" func main() { fmt.Println("This is a placeholder for Go code.") } ``` -------------------------------- ### Verify Message with Upstash QStash Receiver Source: https://upstash.com/docs/redis/howto/vercelintegration Illustrates how to use the Upstash QStash receiver to verify incoming webhook signatures. Requires the '@upstash/qstash' package and signing key environment variables. ```typescript import { Receiver } from "@upstash/qstash"; const receiver = new Receiver({ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY, }); const isValid = await receiver.verify({ signature: "..." body: "..." }) ``` -------------------------------- ### Test Todo API Index Route Source: https://upstash.com/docs/redis/tutorials/laravel_caching Uses `curl` to send a GET request to the API endpoint for retrieving todos. This command verifies that the API is functioning correctly and returning data. ```shell curl http://todo-cache.test/api/todos ``` -------------------------------- ### JSON Response for Integer Redis Result Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns an integer value. ```APIDOC ## JSON Response for Integer Result ### Description Example of a JSON response from the Upstash REST API when a Redis command returns an integer value. ### Response Example ```json { "result": 137 } ``` ``` -------------------------------- ### Waiting Room with Cloudflare Workers and Serverless Redis Source: https://upstash.com/docs/redis/overall/llms-txt Example snippet for a Cloudflare Worker that could be part of a waiting room implementation using Upstash Serverless Redis. ```APIDOC ## Cloudflare Worker Example ### Description Basic structure of a Cloudflare Worker. This can be extended to interact with Upstash Redis for features like waiting rooms. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```Cloudflare Workers export default { async fetch(request) { return new Response("Hello from Cloudflare Workers!"); } }; ``` ### Response N/A (Code Example) ``` -------------------------------- ### HVALS - Get All Hash Values Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hvals Retrieves all values associated with fields in a hash stored at the specified key. If the key does not exist or is not a hash, an empty list is returned. ```APIDOC ## GET /hvals ### Description Returns all values in the hash stored at key. ### Method GET ### Endpoint /hvals ### Parameters #### Query Parameters - **key** (str) - Required - The key of the hash. ### Response #### Success Response (200) - **values** (List[str]) - Required - All values in the hash, or an empty list when key does not exist. #### Response Example ```json { "values": ["Hello", "World"] } ``` ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) response = redis.hvals("myhash") print(response) # Expected output: ['Hello', 'World'] ``` ``` -------------------------------- ### Python Example for JSON.FORGET Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `JSON.FORGET` command with the Python client for Upstash Redis, demonstrating how to delete a specific path within a JSON document. ```APIDOC ## JSON.FORGET Command (Python) ### Description Deletes the specified path within a JSON document stored at the given key. ### Method `redis.json().forget(key: str, path: str): int ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client # Assuming 'key' and the JSON structure are defined # Delete the value at the path '$.path.to.value' redis.json().forget(key, "$.path.to.value") ``` ### Response #### Success Response - **int**: The number of elements that were removed. This is typically 1 if the path existed and was removed, or 0 otherwise. #### Response Example ```json 1 ``` ``` -------------------------------- ### JSON Response for Array Redis Result Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns an array value. ```APIDOC ## JSON Response for Array Result ### Description Example of a JSON response from the Upstash REST API when a Redis command returns an array value. ### Response Example ```json { "result": ["value1", null, "value2"] } ``` ``` -------------------------------- ### Upstash Redis SET Command Examples in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates basic key-value setting, setting expirations using the 'ex' option, and conditional updates using the 'xx' option with the Upstash Redis client in TypeScript. ```TypeScript await redis.set("my-key", {my: "value"}); ``` ```TypeScript await redis.set("my-key", {my: "value"}, { ex: 60 }); ``` ```TypeScript await redis.set("my-key", {my: "value"}, { xx: true }); ``` -------------------------------- ### Serverless Framework Configuration (serverless.yml) Source: https://upstash.com/docs/redis/tutorials/histogram Configuration file for the Serverless Framework. It defines the service name, AWS provider settings including the Node.js runtime and environment variables (like REDIS_URL), and configures two HTTP API endpoints: '/record' (POST) and '/get' (GET). ```yaml service: histogram-api frameworkVersion: "2" provider: name: aws runtime: nodejs12.x lambdaHashingVersion: 20201221 environment: REDIS_URL: REPLACE_YOUR_URL_HERE functions: record: handler: handler.record events: - httpApi: path: /record method: post cors: true get: handler: handler.get events: - httpApi: path: /get method: get cors: true ``` -------------------------------- ### JSON Response for String Redis Result Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns a string value. ```APIDOC ## JSON Response for String Result ### Description Example of a JSON response from the Upstash REST API when a Redis command returns a string value. ### Response Example ```json { "result": "value" } ``` ``` -------------------------------- ### ZPOPMAX Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the ZPOPMAX command, outlining its required and optional arguments, and the structure of its returned response. ```APIDOC ## ZPOPMAX Command API Documentation ### Description Removes and returns the member with the highest score from the sorted set. ### Method POST ### Endpoint `/redis/commands ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "command": "zpopmax", "key": "", "count": "" } ``` ### Parameters Details #### Key - **key** (str) - Required - The key of the sorted set. - **count** (int) - Optional - The number of members to pop. ### Request Example ```python # Assuming 'redis' is a configured Redis client instance result = redis.zpopmax('my_sorted_set', count=1) ``` ### Response #### Success Response (200) - **List[Tuple[str, float]]**: A list of tuples, where each tuple contains the popped member (string) and its score (float). #### Response Example ```json [ ["member1", 10.5], ["member2", 9.8] ] ``` ``` -------------------------------- ### Build Survey App with Upstash Redis in Next.js Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates building a survey application using Upstash Redis with Next.js. This example focuses on managing survey data and responses efficiently. It's a placeholder and requires further implementation. ```javascript console.log('This is a placeholder for Next.js code related to survey app.'); ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt This shell command changes the current working directory to the specified project folder, 'aws-java-counter-api'. This is a common step after creating a new project to continue with its setup and development. ```shell cd aws-java-counter-api ``` -------------------------------- ### TypeScript LPUSHX on Non-existent List Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the behavior of `lpushx` when attempting to push to a Redis list that does not exist. The command returns 0, indicating no elements were pushed and the list was not created. This is useful for conditional list operations. ```TypeScript const length = await redis.lpushx("key", "a"); console.log(length); // 0 ``` -------------------------------- ### TypeScript XADD with Trimming Options Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates appending an entry to a Redis stream while simultaneously applying trimming rules. This example uses `MAXLEN` to limit the stream's length to 1000 entries. ```APIDOC ## TypeScript XADD with Trimming Options ### Description Illustrates appending an entry to a Redis stream while simultaneously applying trimming rules. This example uses `MAXLEN` to limit the stream's length to 1000 entries. ### Language TypeScript ### Code ```ts await redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }); ``` ``` -------------------------------- ### JSON.ARRPOP API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed documentation for the `JSON.ARRPOP` command, outlining its arguments, their types, default values, and the structure of its response. ```APIDOC ## JSON.ARRPOP API Reference ### Description Detailed documentation for the `JSON.ARRPOP` command, outlining its arguments, their types, default values, and the structure of its response. ### Method `JSON.ARRPOP` ### Parameters #### Arguments - **key** (str, required): The key of the JSON entry. - **path** (str, optional, default: "$"): The path of the array. - **index** (int, optional, default: -1): The index of the element to pop. ### Response - **Type**: `List[TValue | null]` - **Description**: The popped element or null if the array is empty. ``` -------------------------------- ### Fastly Compute Publish and Backend Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Publishes a Fastly Compute service and configures a backend for Upstash Redis. This involves creating a new service, defining a domain, and setting up the Redis hostname and port. It requires the Fastly CLI. ```shell > fastly compute publish ✓ Initializing... ✓ Verifying package manifest... ✓ Verifying local javascript toolchain... ✓ Building package using javascript toolchain... ✓ Creating package archive... SUCCESS: Built package 'fastly-upstash' (pkg/fastly-upstash.tar.gz) There is no Fastly service associated with this package. To connect to an existing service add the Service ID to the fastly.toml file, otherwise follow the prompts to create a service now. Press ^C at any time to quit. Create new service: [y/N] y ✓ Initializing... ✓ Creating service... Domain: [supposedly-included-corgi.edgecompute.app] Backend (hostname or IP address, or leave blank to stop adding backends): global-concise-scorpion-30984.upstash.io Backend port number: [80] 443 Backend name: [backend_1] upstash Backend (hostname or IP address, or leave blank to stop adding backends): ✓ Creating domain 'supposedly-smart-corgi.edgecompute.app'... ✓ Creating backend 'upstash' (host: global-concise-scorpion-30984.upstash.io, port: 443)... ✓ Uploading package... ✓ Activating version... ``` -------------------------------- ### TypeScript: HKEYS Hash Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to set a Redis hash using `hset` and then retrieve all its field names using `hkeys` in TypeScript. Displays the expected output of the field names. Requires an Upstash Redis client. ```typescript await redis.hset("key", { id: 1, username: "chronark", }); const fields = await redis.hkeys("key"); console.log(fields); // ["id", "username"] ``` -------------------------------- ### Upstash REST API URL Mapping for Redis Commands Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples demonstrating how various Redis commands are translated into corresponding URL paths for the Upstash REST API. ```APIDOC ## Upstash REST API URL Mapping for Redis Commands ### Description This section illustrates how common Redis commands map to URL paths when using the Upstash REST API. This is useful for direct HTTP requests to your Redis instance. ### Method Not Applicable (URL mapping examples) ### Endpoint Not Applicable (URL mapping examples) ### Parameters Not Applicable (URL mapping examples) ### Request Example ```bash - `SET foo bar` -> `REST_URL/set/foo/bar` - `SET foo bar EX 100` -> `REST_URL/set/foo/bar/EX/100` - `GET foo` -> `REST_URL/get/foo` - `MGET foo1 foo2 foo3` -> `REST_URL/mget/foo1/foo2/foo3` - `HGET employee:23381 salary` -> `REST_URL/hget/employee:23381/salary` - `ZADD teams 100 team-x 90 team-y` -> `REST_URL/zadd/teams/100/team-x/90/team-y` ``` ### Response Not Applicable (URL mapping examples) ``` -------------------------------- ### Initialize AWS CDK Project Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new AWS CDK application within the current directory, setting up the basic project structure with TypeScript as the chosen language. ```APIDOC ## Initialize AWS CDK Project ### Description Initializes a new AWS CDK application with TypeScript as the chosen language. ### Method Shell command ### Endpoint N/A ### Parameters None ### Request Example ```bash cdk init app --language typescript ``` ### Response N/A ``` -------------------------------- ### Navigate to Phoenix Project Directory (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt A standard shell command to change the current directory to 'redix_demo'. This is typically used after generating a new Phoenix project to access its files and proceed with development setup. ```shell cd redix_demo ``` -------------------------------- ### TypeScript Example for JSON.MERGE Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `JSON.MERGE` command with the Upstash Redis client in TypeScript to merge a new object into a specific path within a JSON document. ```APIDOC ## JSON.MERGE Command (TypeScript) ### Description Merges a new object into a specific path within a JSON document stored in Redis. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```ts await redis.json.merge("key", "$.path.to.value", {"new": "value"}) ``` ### Response N/A (Code Example) ``` -------------------------------- ### Connect to Upstash Redis with Redisson and Perform Basic Operations Source: https://upstash.com/docs/redis/overall/llms-txt This Java code snippet demonstrates how to initialize the Redisson client, connect to an Upstash Redis instance using a password and endpoint, and perform a basic `put` and `get` operation on a distributed map (`RMap`). ```APIDOC ## Connect to Upstash Redis with Redisson and Perform Basic Operations ### Description This Java code snippet demonstrates how to initialize the Redisson client, connect to an Upstash Redis instance using a password and endpoint, and perform a basic `put` and `get` operation on a distributed map (`RMap`). Remember to replace placeholders for password and endpoint, and use `rediss://` for SSL connections. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```Java import org.redisson.Redisson; import org.redisson.api.RMap; import org.redisson.config.Config; public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") // use "rediss://" for SSL connection .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ``` ### Response N/A (SDK Example) ``` -------------------------------- ### XRANGE Command Usage (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `xrange` method with a TypeScript Redis client, showing the basic invocation with start and end IDs, and the expected console output format of the stream entries. ```APIDOC ## XRANGE ### Description Returns a range of entries in the stream associated with the given key, between. ### Method GET ### Endpoint `/stream/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the stream. #### Query Parameters - **start** (string) - Required - The start ID of the range. Use `-" for the first entry. - **stop** (string) - Required - The stop ID of the range. Use `+" for the last entry. - **count** (integer) - Optional - The maximum number of entries to return. - **withvalues** (boolean) - Optional - If true, return the elements of the stream entries. ### Request Example ```javascript redis.xrange(key, "-", "+"); ``` ### Response #### Success Response (200) - **entries** (object) - An object where keys are entry IDs and values are the entry data. #### Response Example ```json { "1548149259438-0": { "field1": "value1", "field2": "value2" }, "1548149259438-1": { "field1": "value3", "field2": "value4" } } ``` ``` -------------------------------- ### TypeScript: Basic Write and Read Operations Source: https://upstash.com/docs/redis/howto/readyourwrites Demonstrates basic set and get operations using the Upstash Redis TypeScript SDK. This function writes a random key-value pair and returns the key. It initializes a Redis client from environment variables. ```typescript import { Redis } from "@upstash/redis"; import { nanoid } from "nanoid"; export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; ``` -------------------------------- ### Monitor Upstash Redis Commands (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates how to use the `ioredis` client to connect to an Upstash Redis database and set up a real-time monitor. It listens for the 'monitor' event, logging details of each executed command, including timestamp, arguments, source, and database, to the console. ```APIDOC ## Monitor Upstash Redis Commands (TypeScript) ### Description Demonstrates how to use the `ioredis` client to connect to an Upstash Redis database and set up a real-time monitor. It listens for the 'monitor' event, logging details of each executed command to the console. ### Request Example ```ts const monitor = await redis.monitor() monitor.on("monitor", (time, args, source, database) => { console.log(time, args, source, database) }) ``` ``` -------------------------------- ### Get Bit from Redis Bitset (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/bitmap/getbit Retrieves a single bit from a specified key at a given offset in a Redis bitset. This command is useful for managing bit-level data structures. ```typescript const bit = await redis.getbit(key, 4); ``` -------------------------------- ### Create a new Phoenix Elixir application without Ecto Source: https://upstash.com/docs/redis/overall/llms-txt This command initializes a new Phoenix application named `redix_demo`. The `--no-ecto` flag is used to disable the default Ecto datastore setup, as the application will exclusively use Redis for data storage, simplifying the project configuration. ```APIDOC ## Create a new Phoenix Elixir application without Ecto ### Description Initializes a new Phoenix application named `redix_demo` without Ecto, configured to use Redis for data storage. ### Command ```shell mix phx.new redix_demo --no-ecto ``` ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new directory named `counter-cdk` and navigates into it. This directory will serve as the root for the AWS CDK project. ```APIDOC ## Create Project Directory ### Description This command creates a new directory for an AWS CDK project and changes the current directory to it. ### Command ```shell mkdir counter-cdk && cd counter-cdk ``` ``` -------------------------------- ### XRANGE Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documents the XRANGE command for Redis streams, detailing its required arguments (key, start, end) and optional arguments (count), along with the structure of its response. ```APIDOC ## XRANGE Command ### Description Returns stream entries matching a given range of IDs. ### Method GET (or equivalent for stream range retrieval) ### Endpoint `/stream/{key}` (conceptual endpoint for range retrieval) ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. #### Query Parameters - **start** (str) - Required - The stream entry ID to start from. - **end** (str) - Required - The stream entry ID to end at. - **count** (int) - Optional - The maximum number of entries to return. ### Request Example ```json { "command": "XRANGE", "key": "my_stream", "start": "0-0", "end": "+", "count": 10 } ``` ### Response #### Success Response (200) - **Record>** - An object of stream entries, keyed by their stream ID. #### Response Example ```json { "1678881120000-0": { "sensor-id": "123", "temperature": "25.5" }, "1678881125000-0": { "sensor-id": "123", "temperature": "26.1" } } ``` ``` -------------------------------- ### Run Node.js Application with Local Redis Tunnel Source: https://upstash.com/docs/redis/overall/llms-txt This command is used to start a Node.js application locally. When the `fly redis connect` tunnel is active, the application will seamlessly connect to the Redis instance through this tunnel. ```APIDOC ## Run Node.js Application with Local Redis Tunnel ### Description This command is used to start a Node.js application locally. When the `fly redis connect` tunnel is active, the application will seamlessly connect to the Redis instance through this tunnel, simulating a local Redis setup for development and testing. ### Method Shell command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell npm start ``` ### Response N/A ``` -------------------------------- ### ZUNIONSTORE Command Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates various use cases of the ZUNIONSTORE command in TypeScript, including basic set union, applying custom weights to input sets, and using different aggregation methods like 'sum'. ```APIDOC ## ZUNIONSTORE Command (TypeScript) ### Description Compute the union of multiple sorted sets and store the result in a new sorted set. ### Method ZUNIONSTORE ### Endpoint N/A (SDK usage) ### Parameters #### Arguments - **destination** (string) - Required - The key of the new sorted set. - **numkeys** (number) - Required - The number of input sorted sets. - **keys** (Array) - Required - An array of keys of the input sorted sets. - **options** (object) - Optional - Options for weights and aggregation. - **weights** (Array) - Optional - Weights to apply to each input set. - **aggregate** (string) - Optional - Aggregation method ('SUM', 'MIN', 'MAX'). ### Request Example 1 (Basic Union) ```typescript await redis.zadd("key1", { score: 1, member: "member1" }); await redis.zadd("key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }); const res = await redis.zunionstore("destination", 2, ["key1", "key2"]); console.log(res) // 2 ``` ### Request Example 2 (With Weights) ```typescript await redis.zadd("key1", { score: 1, member: "member1" }); await redis.zadd("key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }); const res = await redis.zunionstore("destination", 2, ["key1", "key2"], { weights: [2, 3] }); console.log(res) // 2 ``` ### Request Example 3 (With Aggregation) ```typescript await redis.zadd("key1", { score: 1, member: "member1" }); await redis.zadd("key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }); const res = await redis.zunionstore("destination", 2, ["key1", "key2"], { aggregate: "sum" }); console.log(res) // 2 ``` ### Response #### Success Response (200) - **result** (number) - The number of elements in the new sorted set. ``` -------------------------------- ### Upstash Redis LPOS: Find element index in a list (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/lpos Demonstrates how to use the LPOS command to find the index of an element in a Redis list. This example uses the Upstash Redis client for TypeScript. ```typescript await redis.rpush("key", "a", "b", "c"); const index = await redis.lpos("key", "b"); console.log(index); // 1 ``` ```typescript await redis.rpush("key", "a", "b", "c", "b"); const index = await redis.lpos("key", "b", { rank: 2 }); console.log(index); // 3 ``` ```typescript await redis.rpush("key", "a", "b", "b"); const positions = await redis.lpos("key", "b", { count: 2 }); console.log(positions); // [1, 2] ``` -------------------------------- ### Create Upstash Redis Instance using Fly CLI Source: https://upstash.com/docs/redis/quickstarts/fly This command initiates the creation of an Upstash Redis database instance through the Fly CLI. It prompts the user to select an organization, choose a name for the database, set a primary region, and decide on memory eviction policies and plan. ```shell > flyctl redis create ? Select Organization: upstash (upstash) ? Choose a Redis database name (leave blank to generate one): ? Choose a primary region (can't be changed later) San Jose, California (US) (sjc) Upstash Redis can evict objects when memory is full. This is useful when caching in Redis. This setting can be changed later. Learn more at https://fly.io/docs/reference/redis/#memory-limits-and-object-eviction-policies ? Would you like to enable eviction? No ? Optionally, choose one or more replica regions (can be changed later): ? Select an Upstash Redis plan 3G: 3 GB Max Data Size Your Upstash Redis database silent-tree-6201 is ready. Apps in the upstash org can connect to at redis://default:978ba2e07tyrt67598acd8ac916a@fly-silent-tree-6201.upstash.io If you have redis-cli installed, use fly redis connect to connect to your database. ``` -------------------------------- ### Iterate All Members of a Sorted Set with ZSCAN (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Python example demonstrating the use of the ZSCAN command to retrieve all members and their scores from a sorted set, handling pagination. ```APIDOC ## Iterate All Members of a Sorted Set with ZSCAN (Python) ### Description This Python code snippet shows how to retrieve all elements from a Redis sorted set using the ZSCAN command, handling cursor-based pagination. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/commands/zset/zscan` ### Parameters #### Query Parameters - **key** (string) - Required - The key of the sorted set. - **cursor** (integer) - Required (initially 0) - The cursor for the scan operation. Use the returned cursor for subsequent calls. - **match** (string) - Optional - A pattern to filter the returned elements. ### Request Example ```python import redis r = redis.Redis.from_url("redis://:@:") # Replace with your connection details cursor = 0 results = [] while True: cursor, keys = r.zscan("myzset", cursor, match="*") # Replace "myzset" with your key results.extend(keys) if cursor == 0: break for key, score in results: print(f"Member: {key.decode()}, Score: {score}") ``` ### Response #### Success Response (200) - **members** (Array) - An array of objects, where each object contains a `member` and its `score`. #### Response Example ```json [ {"member": "member1", "score": 10.5}, {"member": "member2", "score": 20.0} ] ``` ``` -------------------------------- ### TYPE - Get Key Type Source: https://upstash.com/docs/redis/sdks/ts/commands/generic/type Retrieves the type of a given key in the Redis data store. This command is useful for understanding the data structure associated with a key before performing operations. ```APIDOC ## TYPE /key ### Description Get the type of a key. ### Method GET ### Endpoint /key ### Parameters #### Query Parameters - **key** (string) - Required - The key to get. ### Request Example ```ts await redis.type("key"); ``` ### Response #### Success Response (200) - **type** (string) - Required - The type of the key. One of `string` | `list` | `set` | `zset` | `hash` | `none` #### Response Example ```json { "type": "string" } ``` ``` -------------------------------- ### Multi-Regional Sliding Window Ratelimiter (TypeScript) Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/algorithms Creates a multi-regional ratelimiter using the Sliding Window algorithm. Note: This is not recommended due to high command usage and processing times; the Fixed Window algorithm is preferred for multi-region setups. ```typescript const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), }); ``` -------------------------------- ### ZUNIONSTORE Command Example (Redis) Source: https://upstash.com/docs/redis/overall/llms-txt This snippet represents the raw Redis command for ZUNIONSTORE, which is used to merge multiple sorted sets into a new sorted set. The command itself doesn't require a specific programming language SDK to be present in this context. ```redis ZUNIONSTORE ``` -------------------------------- ### MSETNX Command API Documentation for Python and TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the MSETNX command, which sets multiple keys simultaneously only if none of them already exist. This functionality is available in both Python and TypeScript SDKs. It details arguments and the boolean response indicating success. ```apidoc MSETNX Command: Description: Set multiple keys in one go unless they exist already. Counts as a single command for billing. Arguments: ParamField: type: Record required: true description: An object where the keys are the keys to set, and the values are the values to set. Response: ResponseField: type: boolean required: true description: True if all keys were set, False if at least one key was not set. ``` ```apidoc MSETNX Command: Description: Set multiple keys in one go unless they exist already. Counts as a single command for billing. Arguments: - name: keysAndValues type: Record required: true description: An object where the keys are the keys to set, and the values are the values to set. Response: type: number description: '1' if all keys were set, '0' if at least one key was not set. ``` -------------------------------- ### TypeScript Example for JSON.DEL Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.json.del` method in TypeScript to delete a specific path within a JSON document stored in Upstash Redis. ```APIDOC ## TypeScript JSON.DEL Example ### Description Deletes a specific path within a JSON document stored in Upstash Redis using the `json.del` method. ### Method `POST` ### Endpoint `/json/del` ### Parameters #### Request Body - **key** (string) - Required - The key of the JSON document. - **path** (string) - Required - The JSON path to the value to delete. ### Request Example ```json { "key": "key", "path": "$.path.to.value" } ``` ### Response #### Success Response (200) - **(integer)** - The number of paths that were removed. #### Response Example ```json 1 ``` ### Code Example ```ts await redis.json.del("key", "$.path.to.value"); ``` ``` -------------------------------- ### Initialize BullMQ Queue with Upstash Redis (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize a BullMQ Queue and connect it to an Upstash Redis instance. It includes adding jobs to the queue. Requires the 'bullmq' package. ```javascript import { Queue } from 'bullmq'; const myQueue = new Queue('foo', { connection: { host: "UPSTASH_REDIS_ENDPOINT", port: 6379, password: "UPSTASH_REDIS_PASSWORD", tls: {} } }); async function addJobs() { await myQueue.add('myJobName', { foo: 'bar' }); await myQueue.add('myJobName', { qux: 'baz' }); } await addJobs(); ``` -------------------------------- ### BitFieldCommands API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Provides detailed API documentation for the BitFieldCommands instance, which allows for chained bitfield operations in Redis. Includes definitions for get, set, and incr methods, along with general arguments and response structure. ```APIDOC ## BitFieldCommands API Reference ### Description Instance returned by the `redis.bitfield()` function for executing multiple bitfield operations. ### Arguments #### Path Parameters - **key** (str) - Required - The string key to operate on. ### Methods #### GET - **description**: Returns a value from the bitfield at the given offset. - **parameters**: - **type** (str) - e.g., 'u4', 'i8' - **offset** (int) #### SET - **description**: Sets a value and returns the old value. - **parameters**: - **type** (str) - **offset** (int) - **value** (int) #### INCR - **description**: Increments a value and returns the new value. - **parameters**: - **type** (str) - **offset** (int) - **increment** (int) ### Response - **type**: List[int] - **required**: true - **description**: A list of integers, one for each operation executed. ``` -------------------------------- ### Django View for Upstash Redis Counter Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime This Python code defines a Django view that increments a Redis counter and displays its value. It uses the `upstash-redis` library to interact with the Redis database, fetching credentials from environment variables. ```py from datetime import datetime from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') html = f'''

Counter: { count } ''' return HttpResponse(html) ``` -------------------------------- ### PTTL - Get Key Expiration in Milliseconds Source: https://upstash.com/docs/redis/sdks/py/commands/generic/pttl Retrieves the expiration time in milliseconds for a given key in Upstash Redis. Returns a negative value if the key does not exist or has no expiration. ```APIDOC ## GET /pttl ### Description Return the expiration in milliseconds of a key. ### Method GET ### Endpoint /pttl ### Parameters #### Query Parameters - **key** (str) - Required - The key whose expiration time needs to be retrieved. ### Response #### Success Response (200) - **expiration_ms** (int) - The number of milliseconds until this expires, negative if the key does not exist or does not have an expiration set. #### Response Example ```json { "expiration_ms": 10000 } ``` #### Error Response (400) - **error** (str) - Description of the error. #### Error Response Example ```json { "error": "Invalid key provided" } ``` ``` -------------------------------- ### Upstash REST API URL Mapping for Redis Commands Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples demonstrating how various Redis commands are translated into corresponding URL paths for the Upstash REST API, following the Redis Protocol convention. ```shell - `SET foo bar` -> `REST_URL/set/foo/bar` - `SET foo bar EX 100` -> `REST_URL/set/foo/bar/EX/100` - `GET foo` -> `REST_URL/get/foo` - `MGET foo1 foo2 foo3` -> `REST_URL/mget/foo1/foo2/foo3` - `HGET employee:23381 salary` -> `REST_URL/hget/employee:23381/salary` - `ZADD teams 100 team-x 90 team-y` -> `REST_URL/zadd/teams/100/team-x/90/team-y` ``` -------------------------------- ### Redis ECHO Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Provides a TypeScript example for using the Redis ECHO command with an Upstash Redis client. It sends a message to the server and logs the echoed response. ```typescript const response = await redis.echo("hello world"); console.log(response); // "hello world" ``` -------------------------------- ### Get Random Key with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/generic/randomkey This snippet demonstrates how to fetch a random key from your Upstash Redis database using the `randomkey` command in TypeScript. It requires an initialized Redis client instance. ```typescript const key = await redis.randomkey(); ``` -------------------------------- ### JSON.NUMMULTBY Usage Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the `json.nummultby` command in TypeScript for multiplying a numeric value at a specific JSON path within a Redis JSON document. It shows how to specify the key, the JSON path, and the multiplier. ```TypeScript const newValue = await redis.json.nummultby("key", "$.path.to.value", 2); ``` -------------------------------- ### Serverless Function Remote Invocation Output Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Example JSON output received after successfully invoking the serverless function remotely. This shows the structure of a successful response, including status code and body content. ```json { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true }, "body": "{\"message\":\"Query:ca\",\"result\":[\"CAMBODIA\",\"CAMEROON\",\"CANADA\",\"CAPE VERDE\",\"CAYMAN ISLANDS\"]}" ``` -------------------------------- ### EVAL_RO Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use `eval_ro` in Python to execute a simple Lua script that returns an argument passed to it. This illustrates passing dynamic data to the Lua script via the `args` parameter. ```APIDOC ## EVAL_RO Command Example (Python) ### Description Shows how to use `eval_ro` in Python to execute a simple Lua script that returns an argument passed to it. This illustrates passing dynamic data to the Lua script via the `args` parameter. ### Request Example ```python assert redis.eval_ro("return ARGV[1]", args=["Hello"]) == "Hello" ``` ``` -------------------------------- ### Configure different rate limit algorithms for specific routes (JSON) Source: https://upstash.com/docs/redis/overall/llms-txt Example demonstrating how to configure multiple rate limiting strategies for different API routes using the `strapi-plugin-upstash-ratelimit`. It shows how to apply a fixed-window limit to one route and a token bucket limit to another, both identified by a specific header. ```APIDOC ## POST /api/settings/ratelimit ### Description Configures different rate limiting algorithms for specific API routes within a Strapi application using the `strapi-plugin-upstash-ratelimit`. ### Method POST ### Endpoint /api/settings/ratelimit ### Parameters #### Request Body - **strapi-plugin-upstash-ratelimit** (object) - Required - Plugin configuration. - **enabled** (boolean) - Required - Whether the plugin is enabled. - **resolve** (string) - Required - Path to the plugin implementation. - **config** (object) - Required - Plugin configuration details. - **enabled** (boolean) - Required - Whether rate limiting is enabled. - **token** (string) - Required - Upstash Redis authentication token. - **url** (string) - Required - Upstash Redis URL. - **strategy** (array) - Required - Array of rate limiting strategies. - **methods** (array) - Required - HTTP methods to apply the strategy to. - **path** (string) - Required - API path to apply the strategy to. - **identifierSource** (string) - Required - Source for identifying the client (e.g., header name). - **limiter** (object) - Required - Rate limiting algorithm configuration. - **algorithm** (string) - Required - The rate limiting algorithm (e.g., `fixed-window`, `tokenBucket`). - **tokens** (number) - Required - The maximum number of tokens allowed. - **window** (string) - Required - The time window for the rate limit. - **refillRate** (number) - Optional - The rate at which tokens are refilled for `tokenBucket`. - **prefix** (string) - Optional - A prefix for Redis keys used by the plugin. ### Request Example ```json { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "/api/restaurants/:id", "identifierSource": "header.x-author", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } }, { "methods": ["GET"], "path": "/api/restaurants", "identifierSource": "header.x-author", "limiter": { "algorithm": "tokenBucket", "tokens": 10, "window": "20s", "refillRate": 1 } } ], "prefix": "@strapi" } } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful configuration. #### Response Example ```json { "message": "Rate limit configuration updated successfully." } ``` ``` -------------------------------- ### Upstash Pipelining API Request Syntax Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the `curl` command syntax for sending multiple Redis commands as a batch to the Upstash `/pipeline` endpoint. Commands are sent as a two-dimensional JSON array in the request body. ```APIDOC ## Upstash Pipelining API ### Description Send multiple Redis commands as a batch to the Upstash `/pipeline` endpoint. ### Method POST ### Endpoint `/pipeline` ### Request Body - **commands** (Array>) - Required - A two-dimensional JSON array where each inner array represents a Redis command and its arguments. ### Request Example ```shell curl -X POST https://YOUR_UPSTASH_ENDPOINT/pipeline \ -H "Authorization: Bearer $TOKEN" \ -d ' [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] ' ``` ``` -------------------------------- ### List Configured MCP Servers via Claude CLI Source: https://upstash.com/docs/redis/integrations/mcp This command lists all the MCP servers that are currently configured in your Claude environment. It's useful for verifying that the Upstash MCP server has been added successfully. ```bash claude mcp list ``` -------------------------------- ### Set Key-Value Pair in Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string/set Sets a key to hold a string value. If the value is not a string, it will be JSON.stringified. This basic example demonstrates setting a simple key-value pair. ```typescript await redis.set("my-key", {my: "value"}); ``` -------------------------------- ### Set Up Environment Variables for Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/koyeb These bash commands export the necessary Upstash Redis connection details as environment variables. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are required for the application to connect to your Redis instance. Ensure these are set before running the application. ```bash export UPSTASH_REDIS_REST_URL="" export UPSTASH_REDIS_REST_TOKEN="" ``` -------------------------------- ### Fetch Set Members (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This example shows how to add multiple elements to a Redis set and then retrieve all members of that set using the `smembers` command in TypeScript. It uses the Upstash Redis client. ```ts await redis.sadd("set", "a", "b", "c"); const members = await redis.smembers("set"); console.log(members); // ["a", "b", "c"] ``` -------------------------------- ### Retrieve Keys with Upstash Redis Python SDK Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.keys()` method in Python to fetch keys from Upstash Redis. Examples include matching keys by a specific prefix and retrieving all keys. ```APIDOC ## Retrieve Keys with Upstash Redis Python SDK ### Description This example demonstrates fetching keys from Upstash Redis using the `redis.keys()` method in the Python SDK, showing how to retrieve keys matching a pattern or all keys. ### Method `redis.keys(pattern)` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Retrieve keys with a specific prefix keys = redis.keys("prefix*") ``` ```python # Retrieve all keys keys = redis.keys("*") ``` ### Response #### Success Response - `keys` (list[str]) - A list of keys matching the specified pattern. ``` -------------------------------- ### Check Redis Key Existence with Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `exists` command with a Python Redis client. This example shows setting keys, checking their existence, deleting a key, and then re-checking existence to verify the command's behavior. ```APIDOC ## Check Redis Key Existence with Python ### Description Demonstrates how to use the `exists` command with a Python Redis client. This example shows setting keys, checking their existence, deleting a key, and then re-checking existence to verify the command's behavior. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```python redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ``` ### Response N/A (SDK Example) ``` -------------------------------- ### RPUSH Command Example (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/rpush Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. This function takes a key and one or more elements as input and returns the new length of the list after the operation. Ensure you have the Upstash Redis client initialized. ```typescript const length1 = await redis.rpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.rpush("key", "d"); console.log(length2); // 4 ``` -------------------------------- ### Get Random Field from Hash (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hrandfield Demonstrates how to use the HRANDFIELD command in Python to fetch a single random field from a Redis hash. Assumes a Redis client instance is available. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash") in ["field1", "field2"] ``` -------------------------------- ### TypeScript - JSON.SET Examples Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates various ways to use the `redis.json.set` method in TypeScript, including basic usage and conditional setting with `NX` (set if not exists) and `XX` (set if exists) options. ```APIDOC ## POST /redis/json/set ### Description Set the JSON value at path in key. ### Method POST ### Endpoint /redis/json/set ### Parameters #### Request Body - **key** (string) - Required - The key of the JSON entry. - **path** (string) - Required - The JSON path. - **value** (...any) - Required - The value to set. - **options** (object) - Optional - Options for setting the value. - **nx** (boolean) - If true, only set the key if it does not already exist. - **xx** (boolean) - If true, only set the key if it already exists. ### Request Example ```json { "key": "mykey", "path": "$.path", "value": {"nested": "data"}, "options": {"nx": true} } ``` ### Response #### Success Response (200) - **result** (string) - Indicates success or failure. #### Response Example ```json { "result": "OK" } ``` ``` -------------------------------- ### Python Bitfield Increment Operation Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to increment multiple 4-bit unsigned integer values within a Redis bitfield using the `incr` command. ```APIDOC ## BITFIELD (Python SDK - Increment Operation) ### Description Allows for reading, setting, and performing arithmetic operations on different arbitrary-size bit fields contained within a Redis string. ### Method SDK Method Chaining ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (Python) ```python import redis r = redis.Redis(url="YOUR_REDIS_URL") r.set('my-bitfield-key', '') # Initialize or clear the key # Increment offset 0 by 16 (unsigned 4-bit integer) # Increment offset 4 by 1 (unsigned 4-bit integer) result = r.bitfield('my-bitfield-key') \ .incr('u4', 0, 16) \ .incr('u4', 4, 1) \ .execute() print(f"Result: {result}") # Expected: [0, 1] ``` ### Response #### Success Response (200) - **result** (List[int]) - A list containing the results of each operation in the order they were executed. Each element corresponds to the value of the bitfield *before* the operation was applied. #### Response Example ```python # If the bitfield was initially all zeros, the result would be: # [0, 0] # Because the first operation returns the value before incrementing, and the second does the same. # The subsequent state of the bitfield would reflect the increments. ``` ``` -------------------------------- ### Count Set Bits with BITCOUNT (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/bitmap/bitcount Demonstrates how to use the BITCOUNT command in Upstash Redis to count the number of set bits in a binary string. This example shows the basic usage without specifying a range. ```typescript const bits = await redis.bitcount(key); ``` -------------------------------- ### HEXPIRETIME Usage Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `hexpiretime` command with Upstash Redis in a TypeScript application, including setting a key, expiring a field, and retrieving its expiration time. ```APIDOC ## HEXPIRETIME ### Description Retrieves the expiration time of a field in a hash. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.hset("my-key", "my-field", "my-value"); await redis.hexpireat("my-key", "my-field", Math.floor(Date.now() / 1000) + 10); const expireTime = await redis.hexpiretime("my-key", "my-field"); console.log(expireTime); // e.g., [1697059200] ``` ### Response #### Success Response (200) - **expireTime** (number | null) - The expiration time in seconds, or null if the field does not exist or has no expiration. #### Response Example ```json 1697059200 ``` ``` -------------------------------- ### Node.js: Define @upstash/redis dependency in package.json Source: https://upstash.com/docs/redis/overall/llms-txt Configuration for `package.json` to include `@upstash/redis` as a project dependency. This ensures the Upstash Redis client library is installed and available for use in a Node.js project. ```json { "dependencies": { "@upstash/redis": "latest" } } ``` -------------------------------- ### Prepend Element to Existing List with LPUSHX in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `lpushx` command in TypeScript to prepend an element to a list only if the list already exists. This example first ensures a list exists using `lpush` and then demonstrates `lpushx`, logging the new list length. ```typescript await redis.lpush("key", "a", "b", "c"); const length = await redis.lpushx("key", "d"); console.log(length); // 4 ``` -------------------------------- ### Example ioredis Error Message Source: https://upstash.com/docs/redis/troubleshooting/econn_reset This snippet shows a typical error message encountered when a client cannot connect to the Upstash Redis database due to a connection issue, specifically a read ECONNRESET error. ```text [ioredis] Unhandled error event: Error: read ECONNRESET at TCP.onStreamRead (node:internal/stream_base_commons:211:20) ``` -------------------------------- ### HSCAN Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the HSCAN command in TypeScript for basic scanning, pattern matching, and limiting results. It requires the Upstash Redis client and operates on hash data structures. ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const [newCursor, fields] = await redis.hscan("key", 0); console.log(newCursor); // likely `0` since this is a very small hash console.log(fields); // ["id", 1, "username", "chronark", "name", "andreas"] ``` ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const [newCursor, fields] = await redis.hscan("key", 0, { match: "user*" }); console.log(newCursor); // likely `0` since this is a very small hash console.log(fields); // ["username", "chronark"] ``` ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const [newCursor, fields] = await redis.hscan("key", 0, { count: 2 }); console.log(fields); // ["id", 1, "name", "andreas", "username", "chronark"] ``` -------------------------------- ### Use Redis in Fastly Compute@Edge Source: https://upstash.com/docs/redis/overall/llms-txt This example illustrates how to integrate Upstash Redis within the Fastly Compute@Edge platform. It highlights the use of Redis for edge computing scenarios. It links to an external article for detailed implementation steps. ```jsx Use Redis in Fastly Compute ``` -------------------------------- ### SDIFFSTORE Command API Reference (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Detailed documentation for the SDIFFSTORE command in TypeScript, outlining its required arguments and the structure of its response. ```APIDOC ## SDIFFSTORE Command API Reference ### Description Write the difference between sets to a new set ### Method APICALL ### Endpoint /redis/sdiffstore ### Parameters #### Query Parameters - **destination** (string) - Required - The key of the set to store the resulting set in. - **keys** (string[]) - Required - The keys of the sets to perform the difference operation on. ### Request Example ```json { "destination": "new_set_key", "keys": ["set1", "set2"] } ``` ### Response #### Success Response (200) - **Type** (TValue[]) - The members of the resulting set. #### Response Example ```json ["member1", "member2"] ``` ``` -------------------------------- ### Fetch Weather from Cache (Elixir) Source: https://upstash.com/docs/redis/quickstarts/elixir Retrieves weather data from the Upstash Redis cache using the 'GET' command. Returns the cached data if found, or an error if not found or if a cache retrieval error occurs. Decodes JSON data. ```elixir defp fetch_weather_from_cache(location) do case Redix.command(:redix, ["GET", "weather:#{location}"]) do {:ok, nil} -> {:error, :not_found} {:ok, cached_weather_json} -> {:ok, Jason.decode!(cached_weather_json)} {:error, _reason} -> {:error, "Failed to fetch weather data from cache."} end end ``` -------------------------------- ### SET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the Redis SET command, outlining all supported arguments, their types, descriptions, and the command's expected response. ```APIDOC ## SET Command API Reference ### Description Sets a key to hold a string value. Supports various options for expiration and conditional setting. ### Method `SET` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body N/A ### Arguments - **key** (str, required): The key to set. - **value** (TValue, required): The value to set. If not a string, it will be JSON.stringified. - **get** (bool, optional): If true, returns the old value of the key instead of `True`. Returns `None` if the key did not exist. - **ex** (int, optional): Sets an expiration time in seconds. - **px** (int, optional): Sets an expiration time in milliseconds. - **exat** (int, optional): Sets the expiration time using a UNIX timestamp in seconds. - **pxat** (int, optional): Sets the expiration time using a UNIX timestamp in milliseconds. - **keepttl** (bool, optional): Keeps the existing TTL if the key already exists. - **nx** (bool, optional): Only set the key if it does not already exist. - **xx** (bool, optional): Only set the key if it already exists. ### Response #### Success Response - **(bool/TValue)**: `True` if the key was set. If `get` is specified, returns the old value or `None`. #### Response Example ```json true // Default successful response "old_value" // If 'get' option is used and key existed null // If 'get' option is used and key did not exist ``` ``` -------------------------------- ### Example Usage of LRANGE with Upstash Redis in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `lpush` command to populate a Redis list and then retrieve a specific range of elements using the `lrange` command with an Upstash Redis client in TypeScript. ```APIDOC ## Example Usage of LRANGE with Upstash Redis in TypeScript ### Description Demonstrates how to use the `lpush` command to populate a Redis list and then retrieve a specific range of elements using the `lrange` command with an Upstash Redis client in TypeScript. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```ts await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` ### Response N/A (SDK Example) ``` -------------------------------- ### HPEXPIRETIME Usage Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `hset`, `hpexpireat`, and `hpexpiretime` commands with Upstash Redis in TypeScript to set a field, set its expiration, and then retrieve its expiration time. ```APIDOC ## HPEXPIRETIME ### Description Retrieves the expiration time in milliseconds of a field in a hash. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.hset("my-key", "my-field", "my-value"); await redis.hpexpireat("my-key", "my-field", Date.now() + 1000); const expireTime = await redis.hpexpiretime("my-key", "my-field"); console.log(expireTime); // e.g., 1697059200000 ``` ### Response #### Success Response (200) - **expireTime** (number | null) - The expiration time in milliseconds, or null if the field does not exist or has no expiration. #### Response Example ```json 1697059200000 ``` ``` -------------------------------- ### HSCAN Command Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates various ways to use the HSCAN command with Upstash Redis in TypeScript, including basic scanning, filtering by pattern, and limiting the number of returned fields. ```APIDOC ## HSCAN Command Usage Examples ### Description Demonstrates various ways to use the HSCAN command with Upstash Redis in TypeScript, including basic scanning, filtering by pattern, and limiting the number of returned fields. ### Method POST (Implied by SDK usage) ### Endpoint /redis/v1/command (Implied by SDK usage) ### Request Body Example (for hset) ```json { "command": "HSET", "key": "key", "arguments": { "id": 1, "username": "chronark", "name": "andreas" } } ``` ### Request Body Example (for hscan basic) ```json { "command": "HSCAN", "key": "key", "cursor": 0 } ``` ### Request Body Example (for hscan with match) ```json { "command": "HSCAN", "key": "key", "cursor": 0, "match": "user*" } ``` ### Request Body Example (for hscan with count) ```json { "command": "HSCAN", "key": "key", "cursor": 0, "count": 2 } ``` ### Response Example (for hscan) ```json { "result": [ "0", [ "id", 1, "username", "chronark", "name", "andreas" ] ] } ``` ``` -------------------------------- ### TypeScript: Fixed Window Ratelimiter Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates implementing a fixed window rate limiter using TypeScript and Upstash Redis. This includes examples for both single-region and multi-region configurations, allowing up to 10 requests per 10 seconds. ```typescript const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.fixedWindow(10, "10 s"), }); ``` ```typescript const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"), }); ``` -------------------------------- ### Configure Serverless Framework for AWS Lambda Source: https://upstash.com/docs/redis/tutorials/using_serverless_framework Defines the AWS provider, Node.js runtime, and environment variables for the Serverless Framework service. It also configures a 'counter' function triggered by an HTTP GET request to the root path. ```yaml service: counter-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: counter: handler: handler.counter events: - httpApi: path: / method: get ``` -------------------------------- ### Fetch Limited Number of Stream Entries with XRANGE (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrange Retrieves a limited number of stream entries using the XRANGE command with the 'count' argument. This example fetches up to 10 entries from 'mystream' within the full ID range. ```python result = redis.xrange("mystream", "-", "+", count=10) ``` -------------------------------- ### Implement Redis Increment in Next.js Route Handler Source: https://upstash.com/docs/redis/quickstarts/vercel-functions-app-router Creates a Next.js API route handler (`/app/api/hello/route.ts`) that uses Upstash Redis to increment a counter. It fetches credentials from environment variables and returns the updated count. ```typescript import { Redis } from "@upstash/redis"; import { NextResponse } from "next/server"; const redis = Redis.fromEnv(); export async function GET() { const count = await redis.incr("counter"); return NextResponse.json({ count }); } export const dynamic = 'force-dynamic' ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/redis/tutorials/rate-limiting Changes the current directory to the newly created Serverless project folder. ```shell cd ratelimit-serverless ``` -------------------------------- ### ZREM Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZREM command in Python with the Upstash Redis client. It shows adding initial members to a sorted set and then removing specific members, asserting the count of successfully removed members. ```APIDOC ## ZREM Command Example (Python) ### Description Demonstrates how to use the ZREM command in Python with the Upstash Redis client. It shows adding initial members to a sorted set and then removing specific members, asserting the count of successfully removed members. ### Request Example ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zrem("myset", "one", "four") == 1 ``` ``` -------------------------------- ### Run Container Locally with Docker Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions Command to authenticate Docker with Google Cloud Container Registry and then run the built container image locally. This allows for local testing before deployment. ```bash gcloud auth configure-docker docker run -d -p 8080:8080 gcr.io/cloud-run-sessions/main:v0.1 ``` -------------------------------- ### Redis Transaction Example (Redis) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates a sequence of Redis commands (SET, SETEX, INCR, ZADD) intended to be executed within a single Upstash REST API transaction using the MULTI and EXEC commands. ```redis MULTI SET key1 valuex SETEX key2 13 valuez INCR key1 ZADD myset 11 item1 22 item2 EXEC ``` -------------------------------- ### TypeScript: PERSIST Command with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript code example demonstrating how to use the `persist` method with the Upstash Redis client to remove an expiration time from a key. ```typescript await redis.persist(key); ``` -------------------------------- ### Upsert Data with Upstash Vector Client Source: https://upstash.com/docs/redis/howto/vercelintegration Demonstrates how to initialize the Upstash Vector client and upsert data into an index. Requires the '@upstash/vector' package and UPSTASH_VECTOR_REST_URL/TOKEN environment variables. ```typescript import { Index } from "@upstash/vector"; const index = new Index({ url: process.env.UPSTASH_VECTOR_REST_URL, token: process.env.UPSTASH_VECTOR_REST_TOKEN, }); await index.upsert({ id: "1", data: "Hello world!", metadata: { "category": "greeting" } }) ``` -------------------------------- ### Get Dynamic Rate Limit (TypeScript) Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/methods The `getDynamicLimit` method retrieves the currently set dynamic limit. If no dynamic limit is configured, it returns `null`. This is useful for inspecting the active rate limiting configuration. ```typescript ratelimit.getDynamicLimit(): Promise<{ dynamicLimit: number | null }> ``` ```typescript const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10s"), dynamicLimits: true, }); await ratelimit.setDynamicLimit({ limit: 5 }); const { dynamicLimit } = await ratelimit.getDynamicLimit(); // returns 5 ``` -------------------------------- ### Run Cloudflare Worker Locally with Wrangler Source: https://upstash.com/docs/redis/tutorials/cloudflare_workers_with_redis Starts a local development server for the Cloudflare Worker using the Wrangler CLI. This allows for testing the worker's functionality, including its interaction with Upstash Redis, before deploying. ```shell npx wrangler dev ``` -------------------------------- ### TypeScript Example: Setting Hash Field Expiration Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `hpexpireat` command in TypeScript with an Upstash Redis client to set an expiration time for a hash field. ```APIDOC ## TypeScript Example: Setting Hash Field Expiration ### Description This example demonstrates how to use the `hpexpireat` command in TypeScript with an Upstash Redis client to set an expiration time for a hash field, including a basic setup and logging the result. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```ts await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hpexpireat("my-key", "my-field", Date.now() + 1000); console.log(expirationSet); // [1] ``` ### Response #### Success Response Returns `1` if the expiration was set, `0` if the field does not exist. #### Response Example ```json 1 ``` ``` -------------------------------- ### Retrieve Koyeb Application Domain using Bash Source: https://upstash.com/docs/redis/overall/llms-txt Fetches and displays key details of a deployed Koyeb application, including its ID, name, public access domains, and creation timestamp. This is demonstrated using a bash command. ```bash $ koyeb app get example-koyeb-upstash ``` -------------------------------- ### JSON.TYPE Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `JSON.TYPE` command with the Upstash Redis client in TypeScript to retrieve the type of a JSON value at a specific path within a key. ```APIDOC ## JSON.TYPE Command Example (TypeScript) ### Description Demonstrates how to use the `JSON.TYPE` command with the Upstash Redis client in TypeScript to retrieve the type of a JSON value at a specific path within a key. ### Request Example ```typescript const myType = await redis.json.type("key", "$.path.to.value"); ``` ``` -------------------------------- ### TypeScript: ZPOPMIN Sorted Set Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the ZPOPMIN command in TypeScript to remove and retrieve the smallest element(s) from a Redis sorted set. Requires an Upstash Redis client. ```typescript const popped = await redis.zpopmin("key", 4); ``` -------------------------------- ### STRLEN: Get Length of a String Value (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string Returns the length of the string value stored at a key. If the key does not exist, 0 is returned. This is useful for checking the size of string data. ```typescript const length = await redis.strlen("mykey"); ``` -------------------------------- ### Redis JSON.STRLEN in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates invoking the `redis.json.strlen` method in Python to get the length of a JSON string value at a specified path within a Redis key. ```python redis.json.strlen("key", "$.path.to.str") ``` -------------------------------- ### Connect with redis-py (Python) Source: https://upstash.com/docs/redis/howto/connectclient Connect to Upstash Redis using the redis-py library for Python. This client requires the host, port, password, and explicitly setting ssl=True for TLS. The example demonstrates setting and retrieving a key. ```python import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ``` -------------------------------- ### Initialize AWS CDK Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new directory for the CDK project and navigates into it. This directory name is used by CDK CLI for naming resources. ```APIDOC ## Initialize AWS CDK Project Directory ### Description Creates a new directory for an AWS CDK project and changes the current directory to it. ### Method Shell command ### Endpoint Not applicable (shell command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```shell mkdir counter-cdk && cd counter-cdk ``` ### Response #### Success Response (0) Shell returns exit code 0 upon successful execution. #### Response Example (No direct output, changes current directory) ``` -------------------------------- ### RPOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt API documentation for the RPOP command, including its arguments and response structure. This command is used to remove and get the last element of a list. ```APIDOC ## RPOP Command API Reference ### Description Retrieves and removes the last element from a list. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/commands/list/rpop` ### Parameters #### Query Parameters - **key** (string) - Required - The key of the list. - **count** (integer) - Optional - How many elements to pop. If not specified, a single element is popped. ### Response #### Success Response (200) - **response** (TValue | TValue[] | null) - The popped element(s). If `count` was specified, an array of elements is returned, otherwise a single element is returned. If the list is empty, `null` is returned. #### Response Example ```json { "element": "value" } ``` or ```json { "elements": ["value1", "value2"] } ``` ```json { "elements": null } ``` ``` -------------------------------- ### Redis ZINTERSTORE Usage in Python (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates basic usage of the `redis.zinterstore` command in Python to find the intersection of two sorted sets and store the result in a new destination key. It includes setup and assertion. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinterstore("dest", ["key1", "key2"]) assert result == 1 ``` -------------------------------- ### Get Key Type in Python Source: https://upstash.com/docs/redis/sdks/py/commands/generic/type Retrieves the type of a given key in Redis using Python. It handles string, list, set, zset, hash, and non-existent keys. Requires a Redis client instance. ```python redis.set("key1", "Hello") assert redis.type("key1") == "string" redis.lpush("key2", "Hello") assert redis.type("key2") == "list" assert redis.type("non-existent-key") == "none" ``` -------------------------------- ### HSTRLEN Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt A Python code snippet demonstrating how to call the HSTRLEN command using a Redis client to get the string length of a field within a hash. ```APIDOC ## HSTRLEN ### Description Returns the length of the string value associated with a field in a hash. ### Method GET ### Endpoint `/hash/{key}/{field}/strlen` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the hash. - **field** (string) - Required - The field within the hash. ### Request Example ```python redis.hstrlen("key", "field") ``` ### Response #### Success Response (200) - **length** (integer) - The length of the string value. #### Response Example ```json 5 ``` ``` -------------------------------- ### Initialize Upstash Redis Client in Vercel (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing an Upstash Redis client in a Vercel application using `Redis.fromEnv()` in TypeScript. This method automatically reads `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from environment variables for seamless connection and includes basic `set` and `get` operations. ```typescript const { Redis } = require("@upstash/redis"); module.exports = async (req, res) => { /** * Redis.fromEnv() will read the following from environment variables: * - UPSTASH_REDIS_REST_URL * - UPSTASH_REDIS_REST_TOKEN */ const redis = Redis.fromEnv(); await redis.set("foo", "bar"); const bar = await redis.get("foo"); res.json({ body: `foo: ${bar}`, }); }; ``` -------------------------------- ### Redis BITPOS Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the Redis BITPOS command. It details the command's purpose, its arguments (key, bit, start, end) with their types and requirements, and the structure of the integer response indicating the position of the first set or clear bit. ```apidoc BITPOS Command: Description: Find the position of the first set or clear bit (bit with a value of 1 or 0) in a Redis string key. Arguments: key: Type: string Required: true Description: The key to search in. bit: Type: 0 | 1 Required: true Description: The key to store the result of the operation in. start: Type: number Required: false Description: The index to start searching at. end: Type: number Required: false Description: The index to stop searching at. Response: Type: integer Required: true Description: The index of the first occurrence of the bit in the string. ``` -------------------------------- ### Cloudflare Workers: Basic Fetch Handler Source: https://upstash.com/docs/redis/overall/llms-txt A basic example of a Cloudflare Worker that handles incoming requests. This snippet demonstrates the fundamental structure for creating serverless applications that can interact with services like Upstash Redis. ```cloudflare_workers export default { async fetch(request) { return new Response("Hello from Cloudflare Workers!"); } }; ``` -------------------------------- ### Check Current Redis Keyspace Notification Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the current value of the `notify-keyspace-events` option using `CONFIG GET`. This verifies which keyspace and keyevent notifications are enabled. ```APIDOC ## CONFIG GET notify-keyspace-events ### Description Retrieves the current configuration for Redis keyspace notifications. ### Method POST ### Endpoint `$UPSTASH_REDIS_REST_URL` ### Parameters #### Request Body - **command** (List[str]) - Required - Should be `["CONFIG", "GET", "notify-keyspace-events"]` ### Request Example ```json ["CONFIG", "GET", "notify-keyspace-events"] ``` ### Response #### Success Response (200) - **response** (List[str]) - Description: A list containing the configuration key and its value, e.g., `["notify-keyspace-events", "gKEA"] #### Error Response (e.g., 400, 401, 404) - **error** (string) - Description: An error message indicating the issue. ``` -------------------------------- ### TypeScript: Execute EVALSHA_RO Command Source: https://upstash.com/docs/redis/overall/llms-txt Example demonstrating how to use the `evalshaRo` method with the Upstash Redis client in TypeScript to execute a cached read-only Lua script by its SHA1 hash. ```APIDOC ## POST /redis/evalsha_ro ### Description Executes a cached read-only Lua script by its SHA1 hash using the Upstash Redis client in TypeScript. ### Method POST ### Endpoint /redis/evalsha_ro ### Parameters #### Request Body - **sha1Hash** (string) - Required - The SHA1 hash of the cached Lua script. - **keys** (string[]) - Optional - An array of keys used by the script. - **args** (any[]) - Optional - Arguments to pass to the script. ### Request Example ```javascript const result = await redis.evalshaRo("fb67a0c03b48ddbk8b4c9b011e779563bdbc28cb", [], ["hello"]); console.log(result) ``` ### Response #### Success Response (200) - **result** (any) - The result of the executed Lua script. #### Response Example ```json "hello" ``` ``` -------------------------------- ### Python: Basic JSON.SET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the basic usage of the `redis.json.set` method in Python to set a JSON value at a specified path within a Redis key. Assumes a Redis client with JSON support is available. ```python redis.json.set(key, "$.path", value) ``` -------------------------------- ### LRANGE Redis Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the LRANGE Redis command, which retrieves a range of elements from a list. It specifies the required key, start, and end indices, and the expected array response. ```apidoc LRANGE: description: Returns the specified elements of the list stored at key. Arguments: key: type: string required: true description: The key of the list. start: type: integer required: true description: The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. end: type: integer required: true description: The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. Response: type: TValue[] required: true description: The list of elements in the specified range. ``` -------------------------------- ### Configure Upstash MCP SSE Server with Proxy Source: https://upstash.com/docs/redis/overall/llms-txt JSON configuration for setting up the Upstash MCP server in `sse` mode, designed for server deployments. This setup uses a `supergateway` proxy. ```APIDOC ## Configure Upstash MCP SSE Server with Proxy ### Description Configuration for running the Upstash MCP server in SSE mode with a supergateway proxy for local client integration. ### Method N/A (Configuration file) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "mcpServers": { "upstash": { "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` ```json { "servers": { "upstash": { "type": "stdio", "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` ``` -------------------------------- ### BITCOUNT Command Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitcount Counts the number of set bits (1s) in a binary string stored at a given key. You can optionally specify a range (start and end) to count bits within a specific portion of the string. ```APIDOC ## BITCOUNT ### Description Counts the number of set bits (1s) in a binary string stored at a given key. You can optionally specify a range (start and end) to count bits within a specific portion of the string. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/v1/cmd` (Illustrative, actual endpoint may vary based on client library) ### Parameters #### Query Parameters - **cmd** (string) - Required - The Redis command to execute, e.g., `BITCOUNT key [start end]` #### Path Parameters None #### Request Body None (Command and arguments are typically passed as query parameters or within the command string itself) ### Request Example ```py # Assuming 'redis' is an Upstash Redis client instance # Set some bits redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) redis.setbit("mykey", 9, 1) # Count bits within a range (bytes 0 to 10) response_with_range = redis.execute_command("BITCOUNT", "mykey", 0, 10) print(response_with_range) # Output: 3 # Count all bits in the string response_without_range = redis.execute_command("BITCOUNT", "mykey") print(response_without_range) # Output: 3 ``` ### Response #### Success Response (200) - **count** (integer) - The number of set bits in the specified range or the entire string. #### Response Example ```json { "result": "3" } ``` ``` -------------------------------- ### Python - Execute Custom Redis Commands Source: https://upstash.com/docs/redis/overall/llms-txt This example illustrates how to execute Redis commands that are not explicitly implemented in the `upstash-redis` client. The `execute` function of the client instance can be used by passing the command and its arguments as a Python list. ```APIDOC ## POST /redis/execute ### Description Execute a custom Redis command not directly supported by the SDK. ### Method POST ### Endpoint /redis/execute ### Parameters #### Request Body - **command** (array) - Required - The Redis command and its arguments as a list. ### Request Example ```json { "command": ["XLEN", "test_stream"] } ``` ### Response #### Success Response (200) - **result** (any) - The result of the executed Redis command. #### Response Example ```json { "result": 5 } ``` ``` -------------------------------- ### Increment JSON Number Value (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Example of using the `redis.json.numincrby` command in TypeScript to increment a number value within a JSON document stored in Upstash Redis. ```APIDOC ## Increment JSON Number Value (TypeScript) ### Description Increments a number value at a specific JSON path within a document stored in Redis. ### Method N/A (SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```typescript const newValue = await redis.json.numincrby("key", "$.path.to.value", 2); ``` ### Response #### Success Response (200) - **Type**: number - **Description**: The new value of the number field after incrementing. #### Response Example ```json 5 ``` ``` -------------------------------- ### Send PING to Upstash Redis Server (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/auth/ping This Python code snippet demonstrates how to send a PING command to an Upstash Redis server and assert that the response is 'PONG'. It requires the 'redis' library to be installed and configured. ```python assert redis.ping() == "PONG" ``` -------------------------------- ### ZINTERSTORE API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Comprehensive documentation for the ZINTERSTORE command, detailing its arguments, their types, default values, and the expected response structure. ```APIDOC ## ZINTERSTORE Command ### Description Calculates the intersection of sets and stores the result in a key. ### Method POST (or equivalent for set operations) ### Endpoint `/zset/zinterstore` (conceptual endpoint for intersection and store) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **destination** (str) - Required - The key to store the result in. - **keys** (List[str]) - Required - The keys of the sets to compare. - **weights** (List[float]) - Optional, default=None - The weights to apply to the sets. - **aggregate** (enum: "SUM" | "MIN" | "MAX") - Optional, default="sum" - The aggregation function to apply to the sets. - **withscores** (bool) - Optional, default=false - Whether to include scores in the result. ### Request Example ```json { "command": "ZINTERSTORE", "destination": "dest_set", "keys": ["key1", "key2"], "weights": [1.0, 0.5], "aggregate": "SUM", "withscores": false } ``` ### Response #### Success Response (200) - **integer** - The number of elements in the resulting set. #### Response Example ```json 2 ``` ``` -------------------------------- ### TypeScript Usage Example for ZREMRANGEBYLEX Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to invoke the `zremrangebylex` command using the Upstash Redis client in TypeScript, demonstrating the removal of elements from a sorted set within a specified lexicographical range. ```APIDOC ## DELETE /redis/zremrangebylex ### Description Removes elements from a sorted set within a specified lexicographical range. ### Method DELETE ### Endpoint /redis/zremrangebylex ### Parameters #### Request Body - **key** (string) - Required - The key of the sorted set. - **minLex** (string) - Required - The minimum lexicographical value. - **maxLex** (string) - Required - The maximum lexicographical value. ### Request Example ```typescript await redis.zremrangebylex("key", "alpha", "omega") ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements removed. #### Response Example ```json { "count": 5 } ``` ``` -------------------------------- ### Create Redis Consumer Group (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xgroup_create Creates a new consumer group for a Redis stream. Arguments include the stream key, group name, and the ID to start consuming from. The 'mkstream' argument can be used to create the stream if it does not exist. Returns 'OK' on success. ```python result = redis.xgroup_create("mystream", "mygroup", "$") ``` ```python result = redis.xgroup_create("newstream", "mygroup", "$", mkstream=True) ``` ```python result = redis.xgroup_create("mystream", "mygroup2", "0-0") ``` -------------------------------- ### Use HRANDFIELD Command with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates TypeScript examples for the `hrandfield` command, demonstrating how to retrieve random fields, multiple random fields, and random fields with their values from a Redis hash. ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const randomField = await redis.hrandfield("key"); console.log(randomField); // one of "id", "username" or "name" ``` ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2); console.log(randomFields); // ["id", "username"] or any other combination ``` ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2, true); console.log(randomFields); // { id: "1", username: "chronark" } or any other combination ``` -------------------------------- ### Dump and Import Redis Data using upstash-redis-dump Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates exporting data from a Redis instance using the `upstash-redis-dump` tool. It shows the command-line arguments for connection and output redirection. ```APIDOC ## Export Redis Data ### Description Exports data from a Redis instance using the `upstash-redis-dump` command-line tool. ### Command `upstash-redis-dump` ### Arguments - `-db` (integer) - Required - The database number to connect to. - `-host` (string) - Required - The Redis host address. - `-port` (integer) - Required - The Redis port number. - `-pass` (string) - Required - The password for Redis authentication. - `-tls` (boolean) - Optional - Enable TLS for the connection. ### Example ```shell $ upstash-redis-dump -db 0 -host eu1-moving-loon-6379.upstash.io -port 6379 -pass PASSWORD -tls > redis.dump Database 0: 9 keys dumped ``` ``` -------------------------------- ### Python - HSET (Set Multiple Fields) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to set multiple fields and their values simultaneously in a Redis hash using the `hset` command in Python, by passing a dictionary of key-value pairs. The example asserts the total number of fields added. ```APIDOC ## POST /redis/hset ### Description Set multiple fields and values in a Redis hash. ### Method POST ### Endpoint /redis/hset ### Parameters #### Request Body - **key** (string) - Required - The key of the hash. - **values** (object) - Required - A dictionary of field-value pairs to set. ### Request Example ```json { "key": "myhash", "values": { "field1": "Hello", "field2": "World" } } ``` ### Response #### Success Response (200) - **result** (integer) - The number of fields that were added to the hash. #### Response Example ```json { "result": 2 } ``` ``` -------------------------------- ### Generic Commands API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documentation for generic key-value commands available in the @upstash/redis SDK. ```APIDOC ## DEL /api/redis/del ### Description Delete one or multiple keys. ### Method DEL ### Endpoint /api/redis/del ### Parameters #### Path Parameters - **key** (string) - Required - The key to delete. - **keys** (string[]) - Optional - Multiple keys to delete. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **count** (integer) - The number of keys deleted. #### Response Example ```json { "count": 1 } ``` ``` ```APIDOC ## EXISTS /api/redis/exists ### Description Determine if a key exists. ### Method EXISTS ### Endpoint /api/redis/exists ### Parameters #### Path Parameters - **key** (string) - Required - The key to check. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **exists** (integer) - 1 if the key exists, 0 otherwise. #### Response Example ```json { "exists": 1 } ``` ``` ```APIDOC ## EXPIRE /api/redis/expire ### Description Set a key's time to live in seconds. ### Method EXPIRE ### Endpoint /api/redis/expire ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **seconds** (integer) - Required - The time to live in seconds. ### Request Example ```json { "key": "mykey", "seconds": 60 } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## EXPIREAT /api/redis/expireat ### Description Set the expiration for a key as a UNIX timestamp. ### Method EXPIREAT ### Endpoint /api/redis/expireat ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **timestamp** (integer) - Required - The expiration timestamp in seconds. ### Request Example ```json { "key": "mykey", "timestamp": 1678886400 } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## KEYS /api/redis/keys ### Description Find all keys matching the given pattern. ### Method KEYS ### Endpoint /api/redis/keys ### Parameters #### Path Parameters - **pattern** (string) - Required - The pattern to match keys against (e.g., "user:*"). ### Request Example ```json { "pattern": "user:*" } ``` ### Response #### Success Response (200) - **keys** (string[]) - An array of keys matching the pattern. #### Response Example ```json { "keys": ["user:1", "user:2"] } ``` ``` ```APIDOC ## PERSIST /api/redis/persist ### Description Remove the expiration from a key. ### Method PERSIST ### Endpoint /api/redis/persist ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove expiration from. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **removed** (integer) - 1 if the expiration was removed, 0 otherwise. #### Response Example ```json { "removed": 1 } ``` ``` ```APIDOC ## PEXPIRE /api/redis/pexpire ### Description Set a key's time to live in milliseconds. ### Method PEXPIRE ### Endpoint /api/redis/pexpire ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **milliseconds** (integer) - Required - The time to live in milliseconds. ### Request Example ```json { "key": "mykey", "milliseconds": 60000 } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## PEXPIREAT /api/redis/pexpireat ### Description Set the expiration for a key as a UNIX timestamp specified in milliseconds. ### Method PEXPIREAT ### Endpoint /api/redis/pexpireat ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **timestamp** (integer) - Required - The expiration timestamp in milliseconds. ### Request Example ```json { "key": "mykey", "timestamp": 1678886400000 } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## PTTL /api/redis/pttl ### Description Get the time to live for a key in milliseconds. ### Method PTTL ### Endpoint /api/redis/pttl ### Parameters #### Path Parameters - **key** (string) - Required - The key to get the time to live for. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **milliseconds** (integer) - The time to live in milliseconds, or -1 if the key has no expiration, or -2 if the key does not exist. #### Response Example ```json { "milliseconds": 50000 } ``` ``` ```APIDOC ## RANDOMKEY /api/redis/randomkey ### Description Return a random key from the keyspace. ### Method RANDOMKEY ### Endpoint /api/redis/randomkey ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **key** (string) - The name of a random key, or null if the database is empty. #### Response Example ```json { "key": "somekey" } ``` ``` ```APIDOC ## RENAME /api/redis/rename ### Description Rename a key. ### Method RENAME ### Endpoint /api/redis/rename ### Parameters #### Path Parameters - **oldKey** (string) - Required - The current name of the key. - **newKey** (string) - Required - The new name for the key. ### Request Example ```json { "oldKey": "mykey", "newKey": "newkey" } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the key was renamed successfully. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## RENAMENX /api/redis/renamenx ### Description Rename a key, only if the new key does not exist. ### Method RENAMENX ### Endpoint /api/redis/renamenx ### Parameters #### Path Parameters - **oldKey** (string) - Required - The current name of the key. - **newKey** (string) - Required - The new name for the key. ### Request Example ```json { "oldKey": "mykey", "newKey": "newkey" } ``` ### Response #### Success Response (200) - **renamed** (integer) - 1 if the key was renamed, 0 if the new key already exists. #### Response Example ```json { "renamed": 1 } ``` ``` ```APIDOC ## SCAN /api/redis/scan ### Description Incrementally iterate the keys space. ### Method SCAN ### Endpoint /api/redis/scan ### Parameters #### Path Parameters - **cursor** (string) - Required - The cursor returned by the last call to SCAN, or 0 to start. - **pattern** (string) - Optional - The pattern to match keys against. - **count** (integer) - Optional - The number of elements to return per page. ### Request Example ```json { "cursor": "0", "pattern": "user:*", "count": 10 } ``` ### Response #### Success Response (200) - **cursor** (string) - The cursor for the next iteration. - **keys** (string[]) - An array of keys matching the pattern. #### Response Example ```json { "cursor": "12345", "keys": ["user:1", "user:2"] } ``` ``` ```APIDOC ## TOUCH /api/redis/touch ### Description Alters the last access time of a key(s). Returns the number of existing keys specified. ### Method TOUCH ### Endpoint /api/redis/touch ### Parameters #### Path Parameters - **keys** (string[]) - Required - The keys to update the access time for. ### Request Example ```json { "keys": ["key1", "key2"] } ``` ### Response #### Success Response (200) - **count** (integer) - The number of existing keys specified. #### Response Example ```json { "count": 2 } ``` ``` ```APIDOC ## TTL /api/redis/ttl ### Description Get the time to live for a key. ### Method TTL ### Endpoint /api/redis/ttl ### Parameters #### Path Parameters - **key** (string) - Required - The key to get the time to live for. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **seconds** (integer) - The time to live in seconds, or -1 if the key has no expiration, or -2 if the key does not exist. #### Response Example ```json { "seconds": 60 } ``` ``` ```APIDOC ## TYPE /api/redis/type ### Description Determine the type stored at key. ### Method TYPE ### Endpoint /api/redis/type ### Parameters #### Path Parameters - **key** (string) - Required - The key to determine the type of. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **type** (string) - The type of the key (e.g., "string", "list", "hash", "set", "zset", "stream", "none"). #### Response Example ```json { "type": "string" } ``` ``` ```APIDOC ## UNLINK /api/redis/unlink ### Description Delete one or more keys. ### Method UNLINK ### Endpoint /api/redis/unlink ### Parameters #### Path Parameters - **key** (string) - Required - The key to delete. - **keys** (string[]) - Optional - Multiple keys to delete. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **count** (integer) - The number of keys deleted. #### Response Example ```json { "count": 1 } ``` ``` -------------------------------- ### Configure Upstash Redis for Caching Source: https://upstash.com/docs/redis/quickstarts/laravel Configures Laravel to use Upstash Redis as the cache store by updating the CACHE_STORE and REDIS_CACHE_DB variables in the .env file. It also shows basic cache put and get operations. ```.env CACHE_STORE="redis" REDIS_CACHE_DB="0" ``` ```php Cache::put('key', 'value', now()->addMinutes(10)); $value = Cache::get('key'); ``` -------------------------------- ### JSON Response for Redis Command Error Source: https://upstash.com/docs/redis/overall/llms-txt Examples of JSON responses from the Upstash REST API when a Redis command fails or is rejected, showing the `error` field with an explanatory message. ```APIDOC ## JSON Response for Redis Command Error ### Description Examples of JSON responses from the Upstash REST API when a Redis command fails or is rejected, showing the `error` field with an explanatory message. ### Method REST API Response ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Error Response - **error** (string) - An explanatory message detailing the reason for the command failure. #### Response Example ```json {"error":"WRONGPASS invalid password"} {"error":"ERR wrong number of arguments for 'get' command"} ``` ``` -------------------------------- ### Example Usage of LRANGE with Upstash Redis in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using `lpush` to add elements to a Redis list and then `lrange` to retrieve a specific range of elements in TypeScript. It logs the retrieved elements to the console. ```typescript await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` -------------------------------- ### JSON.ARRINSERT Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Comprehensive documentation for the `JSON.ARRINSERT` command, outlining its required parameters, their data types, default values, and a description of the command's functionality and expected return value. ```APIDOC ## JSON.ARRINSERT ### Description Insert the JSON values into the array at the specified path before the given index. This operation shifts existing elements to the right. ### Method `JSON.ARRINSERT` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript // Example assuming 'redis' is an initialized Upstash Redis client // await redis.json.arrinsert("mykey", "$", 0, "value1", "value2"); ``` ### Response #### Success Response (200) - new_lengths (integer[]) - An array containing the new lengths of the JSON arrays after insertion. ``` -------------------------------- ### Redis SET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Provides detailed documentation for the Redis SET command, outlining its required and optional arguments, their types, descriptions, and the expected response. This API reference is useful for understanding the full capabilities of the SET command. ```apidoc SET Command: Description: Set a key to hold a string value. Arguments: key: Type: string Required: true Description: The key to set. value: Type: TValue Required: true Description: The value to store. Non-string values are JSON.stringify'd. opts (Optional): Type: object Description: Options to modify SET behavior. Options: get: Type: boolean Description: Returns the old value at key, or null if key did not exist, instead of 'OK'. ex: Type: integer Description: Sets an expiration in seconds. px: Type: integer Description: Sets an expiration in milliseconds. exat: Type: integer Description: Sets an expiration at a specific Unix timestamp (seconds). pxat: Type: integer Description: Sets an expiration at a specific Unix timestamp (milliseconds). keepTtl: Type: boolean Description: Preserves the existing TTL if the key already exists. nx: Type: boolean Description: Only sets the key if it does not already exist. xx: Type: boolean Description: Only sets the key if it already exists. Response: Type: string Value: "OK" (default) or old value (if 'get' option is used) Description: Returns 'OK' on success, or the old value if 'get' option is specified. ``` -------------------------------- ### Toggle JSON Boolean Value (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the `redis.json.toggle` method in TypeScript to toggle a boolean value at a specified JSON path within a Redis key. ```typescript const bool = await redis.json.toggle("key", "$.path.to.bool"); ``` -------------------------------- ### Redis BitField Commands API Reference (APIDOC) Source: https://upstash.com/docs/redis/overall/llms-txt Defines the BitFieldCommands instance for executing multiple bitfield operations in Redis. It specifies methods like 'get', 'set', and 'incr' with their parameters and response structures. ```APIDOC BitFieldCommands: description: Instance returned by the `redis.bitfield()` function for executing multiple bitfield operations. arguments: key: type: str required: true description: The string key to operate on. response: type: List[int] required: true description: A list of integers, one for each operation executed. methods: get(type: str, offset: int) description: Returns a value from the bitfield at the given offset. parameters: type: str (e.g., 'u4', 'i8') offset: int set(type: str, offset: int, value: int) description: Sets a value and returns the old value. parameters: type: str offset: int value: int incr(type: str, offset: int, increment: int) description: Increments a value and returns the new value. parameters: type: str offset: int increment: int ``` -------------------------------- ### Calculate Set Difference with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates how to use the SDIFF command with Upstash Redis to find elements present in one set but not in others. ```APIDOC ## Calculate Set Difference (SDIFF) ### Description Calculates the difference between sets, returning elements present in the first set but not in the subsequent sets. ### Method sadd, sdiff ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const diff = await redis.sdiff("set1", "set2"); console.log(diff); ``` ### Response #### Success Response (200) A list of elements that are in the first set but not in the others. #### Response Example ```typescript ["a", "b"] ``` ``` -------------------------------- ### Get Bit from Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates retrieving a single bit at a specific offset from a key in Redis using the `getbit` method in Python. Assumes 'redis' is an initialized Redis client instance. ```python bit = redis.getbit(key, 4) ``` -------------------------------- ### TypeScript Read-Your-Writes Pattern Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates separating client instances for read and write operations in TypeScript. This pattern highlights potential read-after-write consistency issues if not managed carefully, showing distinct write and read functions. ```typescript export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; const randomKey = await writeRequest(); await readRequest(randomKey); ``` -------------------------------- ### Remove Last Element from List (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/rpop Removes and returns the last element from a Redis list. This example demonstrates popping a single element using the RPOP command. It requires the Upstash Redis client library. ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key"); console.log(element); // "c" ``` -------------------------------- ### Testing Leaderboard API with cURL (Shell) Source: https://upstash.com/docs/redis/tutorials/edge_leaderboard These shell commands demonstrate how to test the Leaderboard API endpoints using cURL. They show how to add new scores via POST requests and retrieve the leaderboard via GET requests, including latency measurement. ```shell curl -X POST http://127.0.0.1:8787\?player\=messi\&score\=13 curl -X POST http://127.0.0.1:8787\?player\=ronaldo\&score\=17 curl -X POST http://127.0.0.1:8787\?player\=benzema\&score\=18 curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ``` -------------------------------- ### TypeScript: RPOP Command Usage for Lists Source: https://upstash.com/docs/redis/overall/llms-txt Illustrative TypeScript code snippets for the RPOP command. Demonstrates popping a single element and multiple elements from the right side of a Redis list. Includes examples of pushing elements first using RPUSH. ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key"); console.log(element); // "c" ``` ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key", 2); console.log(element); // ["c", "b"] ``` -------------------------------- ### SUNIONSTORE Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the `SUNIONSTORE` command, outlining its parameters and the structure of its response. ```APIDOC ## SUNIONSTORE Command API Reference ### Description Stores the members of all sets in the given sets, in a new set. ### Method `SUNIONSTORE destinationKey sourceKey [sourceKey ...]` ### Endpoint Not applicable (Redis command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```APIDOC SUNIONSTORE destinationKey key1 key2 ``` ### Response #### Success Response - `type` (set[str]) - The members of the resulting set. ``` -------------------------------- ### Check Redis Key Existence with Python Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `exists` command in Python to check for the presence of multiple keys in Redis. It includes examples of setting, checking, deleting, and re-checking key existence. ```python redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ``` -------------------------------- ### Get Sorted Set Size with ZCARD (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zcard This snippet demonstrates how to use the ZCARD command in Python to retrieve the number of elements in a sorted set. It requires a Redis client instance and assumes the sorted set has already been populated. ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zcard("myset") == 3 ``` -------------------------------- ### Set Field Expiration in Hash (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/hash/hpexpireat Sets an expiration time for a specific field within a Redis hash. This example demonstrates using the `hpexpireat` command with a timestamp in milliseconds. It requires the 'redis' client to be initialized. ```typescript await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hpexpireat("my-key", "my-field", Date.now() + 1000); console.log(expirationSet); // [1] ``` -------------------------------- ### Redis RANDOMKEY Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Official API documentation for the Redis RANDOMKEY command. This section outlines the command's purpose, specifies that it takes no arguments, and describes the expected string response, including the case for an empty database. ```APIDOC ## RANDOMKEY Command ### Description Returns a random key from database. ### Method N/A (Command Reference) ### Endpoint N/A (Command Reference) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments No arguments. ### Request Example ```json { "command": "RANDOMKEY" } ``` ### Response #### Success Response (200) - **result** (str) - A random key from the database, or `None` when the database is empty. #### Response Example ```json { "result": "some_random_key" } ``` ``` -------------------------------- ### Get Length of Redis List (LLEN) Source: https://upstash.com/docs/redis/overall/llms-txt This APIDOC specifies the LLEN command for Redis lists. It takes a key as a string argument and returns the number of elements in the list at that key. ```APIDOC LLEN Command: Arguments: key: type: string required: true description: The key of the list. Response: type: number required: true description: The length of the list at key. ``` -------------------------------- ### Get Random Field with Value from Hash (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hrandfield Illustrates fetching a random field along with its value from a Redis hash using the HRANDFIELD command with the 'withvalues' argument in Python. This returns a dictionary-like object. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash", count=1, withvalues=True) in [ {"field1": "Hello"}, {"field2": "World"} ] ``` -------------------------------- ### Increment Hash Field Value using HINCRBY in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates how to use the `HINCRBY` command with Upstash Redis in TypeScript to increment a hash field's value. ```APIDOC ## Increment Hash Field Value (HINCRBY) ### Description Increments the integer value of a hash field by a specified amount. If the field or hash does not exist, it is created with the value after the increment. ### Method hset, hincrby ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts await redis.hset("key", { field: 20, }); const after = await redis.hincrby("key", "field", 2); console.log(after); ``` ### Response #### Success Response (200) The new integer value of the hash field after the increment. #### Response Example ```typescript 22 ``` ``` -------------------------------- ### Resolve ReferenceError: fetch is not defined in Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Addresses the 'ReferenceError: fetch is not defined' issue in Node.js environments (v17 and earlier) where `fetch` is not natively supported. It provides a solution by installing and importing `isomorphic-fetch` as a polyfill. ```APIDOC ## Resolve ReferenceError: fetch is not defined in Node.js ### Description Addresses the 'ReferenceError: fetch is not defined' issue in Node.js environments (v17 and earlier) where `fetch` is not natively supported. It provides a solution by installing and importing `isomorphic-fetch` as a polyfill. ### Method NPM Package Installation & TypeScript ### Endpoint N/A ### Parameters None ### Request Example ```bash npm i isomorphic-fetch ``` ```typescript import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` ### Response Success Response (200) - The `fetch` function is now available in the Node.js environment. ### Response Example N/A ``` -------------------------------- ### Create New Phoenix Elixir App without Ecto using Shell Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Phoenix application named 'redix_demo' using the 'mix phx.new' command. The '--no-ecto' flag is used to disable the default Ecto datastore setup, as the application will exclusively use Redis for data storage, simplifying the project configuration. ```shell mix phx.new redix_demo --no-ecto ``` -------------------------------- ### JSON.MSET API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the JSON.MSET command, outlining its required arguments and expected response. ```APIDOC ## JSON.MSET API Reference ### Description Sets multiple JSON values at multiple paths in multiple keys. ### Method POST ### Endpoint /v2/redis/json/mset ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key_path_value_tuples** (Array<[string, string, any]> ) - Required - A list of tuples where each tuple contains a key, a JSON path, and a value. ### Request Example ```json { "key_path_value_tuples": [ ["user:1", "$.name", "Alice"], ["user:1", "$.age", 30], ["user:2", "$.name", "Bob"] ] } ``` ### Response #### Success Response (200) - **type** (boolean) - Returns true if the operation was successful. #### Response Example ```json true ``` ``` -------------------------------- ### Get List Length with LLEN (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/list/llen This snippet demonstrates how to use the LLEN command in Upstash Redis to retrieve the number of elements in a list. It first pushes elements into a list and then asserts the correct length is returned. ```python redis.rpush("key", "a", "b", "c") assert redis.llen("key") == 3 ``` -------------------------------- ### Retrieve Set Members using SMEMBERS (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/set/smembers The SMEMBERS command returns all members of a set stored at the given key. It takes the set key as an argument and returns a set of strings representing the members. This example demonstrates adding members and then retrieving them. ```python redis.sadd("set", "a", "b", "c"); assert redis.smembers("set") == {"a", "b", "c"} ``` -------------------------------- ### Run and Deploy SST Application Source: https://upstash.com/docs/redis/quickstarts/sst-v2 These commands cover running the SST application locally in development mode and deploying it to a production stage. It includes setting production secrets and executing the deployment. ```shell npm run dev cd packages/web npm run dev npx sst secrets set --stage prod UPSTASH_REDIS_REST_URL npx sst secrets set --stage prod UPSTASH_REDIS_REST_TOKEN npx sst deploy --stage prod ``` -------------------------------- ### Next.js Survey App with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Provides an example of building a survey application using Next.js and Upstash Redis. This demonstrates how to use Redis for collecting and managing survey data within a Next.js project. ```jsx Building a Survey App with Upstash Redis and Next.js ``` -------------------------------- ### General Plugin Configuration Parameters Source: https://upstash.com/docs/redis/overall/llms-txt Configure the Upstash Ratelimit Strapi plugin. ```APIDOC ## Plugin Configuration ### Description Parameters to enable or disable the Upstash Ratelimit Strapi plugin. ### Parameters - **enabled** (boolean) - Default: true - Enable or disable the plugin. ### Configuration Example ```json { "enabled": false } ``` ``` -------------------------------- ### Execute Lua Script with EVAL Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript example showcasing the `redis.eval` method for executing a Lua script directly. It shows how to define the script, pass keys and arguments, and log the returned value. ```typescript const script = ` return ARGV[1] ` const result = await redis.eval(script, [], ["hello"]); console.log(result) // "hello" ``` -------------------------------- ### Set Key Expiration with PEXPIREAT (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/generic/pexpireat Sets a timeout on a key using a Unix timestamp in milliseconds. The key will be automatically deleted after the specified time. This example demonstrates setting an expiration 10 minutes from the current time. ```typescript const tenMinutesFromNow = Date.now() + 10 * 60 * 1000; await redis.pexpireat(key, tenMinutesFromNow); ``` -------------------------------- ### Fetch Weather Data from External API and Cache (Elixir) Source: https://upstash.com/docs/redis/overall/llms-txt An Elixir example demonstrating how to fetch weather data from an external API, process it, and cache the response in Redis. This reduces redundant API calls. ```APIDOC ## External API Integration with Redis Caching (Elixir) ### Description This example shows an Elixir function `fetch_weather_from_api` that retrieves weather data from an external API. It uses an environment variable for the API key, caches the response in Redis for 8 hours, and then returns the processed weather information. ### Method GET (for external API call) POST (for caching in Redis) ### Endpoint * External API: `http://api.weatherapi.com/v1/current.json` * Redis Cache: (Assumed Upstash Redis endpoint) ### Parameters * **location** (string) - Required - The location for which to fetch weather data. * **WEATHER_API_KEY** (environment variable) - Required - Your API key for the WeatherAPI. ### Request Example (Conceptual - Elixir Function Call) ```elixir fetch_weather_from_api("London") ``` ### Response #### Success Response (200 for API, Redis set for cache) - **weather_info** (map) - Processed weather data. #### Response Example (Conceptual) ```elixir {:ok, %{ "location": %{"name" => "London"}, "current" => %{"temp_c" => 15.0, "condition" => %{"text" => "Partly cloudy"}} }} ``` ``` -------------------------------- ### Define Python Dependencies for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt This entry specifies the 'upstash-redis' library as a necessary dependency for a Python serverless function. This file is utilized by pip during the Lambda bundling process to ensure the required library is installed. ```txt upstash-redis ``` -------------------------------- ### Python: Retrieve Keys with redis.keys() Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.keys()` method in Python to fetch keys from Upstash Redis. Examples include matching keys by a specific prefix and retrieving all keys. Be cautious when using `keys('*')` in production environments as it can impact performance on large datasets. ```python keys = redis.keys("prefix*") ``` ```python keys = redis.keys("*") ``` -------------------------------- ### Load Lua Library to Redis with TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/functions/load Loads a Lua library into Redis. The library code must start with a shebang line specifying its name and use `redis.register_function` to expose functions. The `replace` option allows overwriting existing libraries. ```typescript const code = `#!lua name=mylib -- Simple function that returns a string redis.register_function( 'helloworld', function() return 'Hello World!' end ) -- Complex function that modifies data with logic local function my_hset(keys, args) local hash = keys[1] local time = redis.call('TIME')[1] return redis.call('HSET', hash, '_last_modified_', time, unpack(args)) end redis.register_function('my_hset', my_hset) `; const libraryName = await redis.functions.load({ code, replace: true }); console.log(libraryName); // "mylib" ``` -------------------------------- ### Increment Redis Key Value with INCRBY (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/string/incrby Demonstrates how to use the INCRBY command in Upstash Redis to increment an integer value associated with a key. This example first sets an initial value and then increments it, showing the final result. ```typescript await redis.set("key", 6); await redis.incrby("key", 4); // returns 10 ``` -------------------------------- ### TypeScript LPOP Command Examples for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the LPOP command in TypeScript to remove and return elements from a list in Upstash Redis. Shows popping a single element and multiple elements, along with their expected output. ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key"); console.log(element); // "a" ``` ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key", 2); console.log(element); // ["a", "b"] ``` -------------------------------- ### Apply Rate Limit for All Routes (JSON) Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/configurations This configuration applies a fixed-window rate limit of 10 requests per 20 seconds to all routes, identifying users by their 'Authorization' header. It requires UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL environment variables. ```json { "strapi-plugin-upstash-ratelimit":{ "enabled":true, "resolve":"./src/plugins/strapi-plugin-upstash-ratelimit", "config":{ "enabled":true, "token":"process.env.UPSTASH_REDIS_REST_TOKEN", "url":"process.env.UPSTASH_REDIS_REST_URL", "strategy":[ { "methods":[ "GET", "POST" ], "path":"*", "identifierSource":"header.Authorization", "limiter":{ "algorithm":"fixed-window", "tokens":10, "window":"20s" } } ], "prefix":"@strapi" } } } ``` -------------------------------- ### Fetch Stream Entries by ID Range with XRANGE (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrange Retrieves stream entries within a specific ID range using the XRANGE command. This example shows how to fetch entries between '1548149259438-0' and '1548149259438-5' from the 'mystream' stream. ```python result = redis.xrange("mystream", "1548149259438-0", "1548149259438-5") ``` -------------------------------- ### Get Multiple Random Fields from Hash (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hrandfield Shows how to retrieve multiple random fields from a Redis hash using the HRANDFIELD command with the 'count' argument in Python. This allows fetching a specified number of fields. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash", count=2) in [ ["field1", "field2"], ["field2", "field1"] ] ``` -------------------------------- ### LPUSH Source: https://upstash.com/docs/redis/sdks/py/commands/overview Prepends one or multiple values to the list. ```APIDOC ## LPUSH ### Description Prepends one or multiple values to the list. ### Method N/A ### Endpoint /redis/sdks/py/commands/list/lpush ### Parameters #### Path Parameters - **key** (string) - Required - The key of the list. - **values** (array) - Required - The values to prepend. ### Request Example ```json { "key": "mylist", "values": ["element0", "element-1"] } ``` ### Response #### Success Response (200) - **integer** (integer) - The length of the list after the push operation. #### Response Example ```json 5 ``` ``` -------------------------------- ### Create Node.js Express App with Upstash Redis Counter Source: https://upstash.com/docs/redis/quickstarts/koyeb This JavaScript code creates a basic Express.js server that uses Upstash Redis to count page visits. It initializes Redis from environment variables and increments a 'counter' key on each request. Ensure you have '@upstash/redis' and 'express' installed. ```javascript // Note: if you are using Node.js version 17 or lower, // change the first line to the following: // const { Redis } = require ("@upstash/redis/with-fetch"); const { Redis } = require("@upstash/redis"); const express = require("express"); const app = express(); const redis = Redis.fromEnv(); app.get("/", async (req, res) => { const value = await redis.get("counter"); await redis.set("counter", parseInt(value || 0) + 1); res.send(`Counter: ${value || 0}`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ```