text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
Start by connecting instantiating a `client` instance and connecting it to a Gradio app that is running on Hugging Face Spaces or generally anywhere on the web.
| Connecting to a running Gradio App | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr"); // a Space that translates from English to French
```
You can also connect to private Spaces by passing in your HF token with the `token` property of the options parameter. You can get your HF token here: https://huggin... | Connecting to a Hugging Face Space | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! You'll need to pass in your [Hugging Face token](https://hug... | Duplicating a Space for private use | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
```js
import { Client } from "@gradio/client";
const app = Client.connect("https://bec81a83-5b5c-471e.gradio.live");
... | Connecting a general Gradio app | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:
```js
import { Client } from "@gradio/client";
Client.connect(
space_name,
{ auth: [username, password] }
)
```
| Connecting to a Gradio app with auth | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client`'s `view_api` method.
For the Whisper Space, we can do this:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/whisper");
const app_info = await app.view_api();
co... | Inspecting the API endpoints | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage.

The View API pag... | The "View API" Page | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The simplest way to make a prediction is simply to call the `.predict()` method with the appropriate arguments:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr");
const result = await app.predict("/predict", ["Hello"]);
```
If there are multiple parameters, then you sh... | Making a prediction | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If the API you are working with can return results over time, or you wish to access information about the status of a job, you can use the iterable interface for more flexibility. This is especially useful for iterative endpoints or generator endpoints that will produce a series of values over time as discrete response... | Using events | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The event interface also allows you to get the status of the running job by instantiating the client with the `events` options passing `status` and `data` as an array:
```ts
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr", {
events: ["status", "data"]
});
```
This ensures... | Status | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The job instance also has a `.cancel()` method that cancels jobs that have been queued but not started. For example, if you run:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr");
const job_one = app.submit("/predict", ["Hello"]);
const job_two = app.submit("/predict", ... | Cancelling Jobs | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
Some Gradio API endpoints do not return a single value, rather they return a series of values. You can listen for these values in real time using the iterable interface:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("gradio/count_generator");
const job = app.submit(0, [9]);
for awai... | Generator Endpoints | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
You generally don't need to install cURL, as it comes pre-installed on many operating systems. Run:
```bash
curl --version
```
to confirm that `curl` is installed. If it is not already installed, you can install it by visiting https://curl.se/download.html.
| Installation | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
To query a Gradio app, you'll need its full URL. This is usually just the URL that the Gradio app is hosted on, for example: https://bec81a83-5b5c-471e.gradio.live
**Hugging Face Spaces**
However, if you are querying a Gradio on Hugging Face Spaces, you will need to use the URL of the embedded Gradio app, not the UR... | Step 0: Get the URL for your Gradio App | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
The first of the two `curl` requests is `POST` request that submits the input payload to the Gradio app.
The syntax of the `POST` request is as follows:
```bash
$ curl -X POST $URL/call/$API_NAME -H "Content-Type: application/json" -d '{
"data": $PAYLOAD
}'
```
Here:
* `$URL` is the URL of the Gradio app as obta... | Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
king a request to a private Space, you will need to pass in a [Hugging Face token](https://huggingface.co/settings/tokens) that has read access to the Space. The request will look like this:
```bash
$ curl -X POST https://private-space.hf.space/call/predict -H "Content-Type: application/json" -H "Authorization: Bearer... | Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
ient?"],
"session_hash": "newsequence5678"
}'
```
| Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
Once you have received the `EVENT_ID` corresponding to your prediction, you can stream the results. Gradio stores these results in a least-recently-used cache in the Gradio app. By default, the cache can store 2,000 results (across all users and endpoints of the app).
To stream the results for your prediction, make ... | Step 2: GET the result | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
```bash
event: generating
data: ["Hello, w!"]
event: generating
data: ["Hello, wo!"]
event: generating
data: ["Hello, wor!"]
event: generating
data: ["Hello, worl!"]
event: generating
data: ["Hello, world!"]
event: complete
data: ["Hello, world!"]
```
**File Example**
If your Gradio app returns a file, the file will ... | Step 2: GET the result | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
What if your Gradio application has [authentication enabled](/guides/sharing-your-appauthentication)? In that case, you'll need to make an additional `POST` request with cURL to authenticate yourself before you make any queries. Here are the complete steps:
First, login with a `POST` request supplying a valid username... | Authentication | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
Use `gradio.Server` instead of `gr.Blocks` when any of the following apply:
- You want a **completely custom (potentially vibe-coded) UI** (your own HTML, React, Svelte, etc.) powered by Gradio's backend
- You want **full FastAPI control** (custom GET/POST routes, middleware, dependency injection) alongside Gradio API... | When to use `gradio.Server` | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
`gradio.Server` is included in the main Gradio package. If you want MCP support, install the extra:
```bash
pip install "gradio[mcp]"
```
| Installation | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
Here's the simplest possible Server mode app — a single API endpoint with no UI:
```python
from gradio import Server
app = Server()
@app.api(name="hello")
def hello(name: str) -> str:
return f"Hello, {name}!"
app.launch()
```
That's it. When you run this script, you get:
- A Gradio API endpoint at `/gradio_ap... | A Minimal Example | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
Since `gradio.Server` inherits from FastAPI, you can add any route directly:
```python
from gradio import Server
from fastapi.responses import HTMLResponse
app = Server()
@app.api(name="hello")
def hello(name: str) -> str:
return f"Hello, {name}!"
@app.get("/", response_class=HTMLResponse)
async def homepage():... | Custom Routes | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
To expose your API endpoints as MCP tools, add the `@app.mcp.tool()` decorator and pass `mcp_server=True` to `launch()`:
```python
from gradio import Server
app = Server()
@app.mcp.tool(name="hello")
@app.api(name="hello")
def hello(name: str) -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
ap... | MCP Tools | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
This example combines everything: custom HTML served at `/`, Gradio API endpoints with concurrency limits, MCP tools, and a custom REST endpoint, and two connected via [the Gradio JavaScript client](/guides/getting-started-with-the-js-client).
$code_server_app
Run it with:
```bash
python run.py
```
Then open `http:... | A Complete Example with the JavaScript Client | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
`app.api()` supports all of the same concurrency and streaming options as `gr.api()`:
```python
@app.api(name="generate", concurrency_limit=2, stream_every=0.5)
async def generate(prompt: str):
for token in model.generate(prompt):
yield token
```
Generator functions automatically stream results via SSE, j... | Concurrency and Streaming | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency. But note that this documentation reflects the latest version of the `gradio_client`, so upgrade if you're not sure!
The lightweight `gradio_client` package can be installed from pip (or pip3) and is tested to work w... | Installation | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Hugging Face Spaces.
```python
from gradio_client import Client
client = Client("abidlabs/en2fr") a Space that translates from English to French
```
You can also connect to private Spaces by passing in your HF t... | Connecting to a Gradio App on Hugging Face Spaces | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,
and then use it to make as many requests as you'd like!
The `gradio_client` includes a class method: `Client.duplic... | Duplicating a Space for private use | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
```python
from gradio_client import Client
client = Client("https://bec81a83-5b5c-471e.gradio.live")
```
| Connecting a general Gradio app | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:
```python
from gradio_client import Client
Client(
space_name,
auth=[username, password]
)
```
| Connecting to a Gradio app with auth | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client.view_api()` method. For the Whisper Space, we see the following:
```bash
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(audio, api_name="/predict") -> output
P... | Inspecting the API endpoints | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage.

The View API pag... | The "View API" Page | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The simplest way to make a prediction is simply to call the `.predict()` function with the appropriate arguments:
```python
from gradio_client import Client
client = Client("abidlabs/en2fr")
client.predict("Hello", api_name='/predict')
>> Bonjour
```
If there are multiple parameters, then you should pass them as se... | Making a prediction | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
```python
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
client.predict(
audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3")
)
>> "My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don'... | Making a prediction | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
One should note that `.predict()` is a _blocking_ operation as it waits for the operation to complete before returning the prediction.
In many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a `Job` instance using the `.submit... | Running jobs asynchronously | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Alternatively, one can add one or more callbacks to perform actions after the job has completed running, like this:
```python
from gradio_client import Client
def print_result(x):
print("The translated result is: {x}")
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict", res... | Adding callbacks | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The `Job` object also allows you to get the status of the running job by calling the `.status()` method. This returns a `StatusUpdate` object with the following attributes: `code` (the status code, one of a set of defined strings representing the status. See the `utils.Status` class), `rank` (the current position of th... | Status | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The `Job` class also has a `.cancel()` instance method that cancels jobs that have been queued but not started. For example, if you run:
```py
client = Client("abidlabs/whisper")
job1 = client.submit(handle_file("audio_sample1.wav"))
job2 = client.submit(handle_file("audio_sample2.wav"))
job1.cancel() will return Fal... | Cancelling Jobs | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Some Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running `job.outputs()`:
```py
from gradio_client import Client
client = Client(src="gradio/count_generator")
job = clie... | Generator Endpoints | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Gradio demos can include [session state](https://www.gradio.app/guides/state-in-blocks), which provides a way for demos to persist information from user interactions within a page session.
For example, consider the following demo, which maintains a list of words that a user has submitted in a `gr.State` component. Whe... | Demos with Session State | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Let's start with what seems like the most complex bit -- using machine learning to remove the music from a video.
Luckily for us, there's an existing Space we can use to make this process easier: [https://huggingface.co/spaces/abidlabs/music-separation](https://huggingface.co/spaces/abidlabs/music-separation). This Sp... | Step 1: Write the Video Processing Function | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
f heavy lifting when it comes to working with audio and video files. The most common way to use `ffmpeg` is through the command line, which we'll call via Python's `subprocess` module:
Our video processing workflow will consist of three steps:
1. First, we start by taking in a video filepath and extracting the audio ... | Step 1: Write the Video Processing Function | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Next up, we'll create a simple FastAPI app. If you haven't used FastAPI before, check out [the great FastAPI docs](https://fastapi.tiangolo.com/). Otherwise, this basic template, which we add to `main.py`, will look pretty familiar:
```python
import os
from fastapi import FastAPI, File, UploadFile, Request
from fastap... | Step 2: Create a FastAPI app (Backend Routes) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Finally, we create the frontend of our web application. First, we create a folder called `templates` in the same directory as `main.py`. We then create a template, `home.html` inside the `templates` folder. Here is the resulting file structure:
```csv
├── main.py
├── templates
│ └── home.html
```
Write the followin... | Step 3: Create a FastAPI app (Frontend Template) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
class="upload-btn">Choose video file</label> <input type="file"
name="video" id="video-upload"> <span class="file-name"></span> <button
type="submit" class="upload-btn">Upload</button> </form> <script> //
Display selected file name in the form const fileUpload =
document.getElementById("video-up... | Step 3: Create a FastAPI app (Frontend Template) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Finally, we are ready to run our FastAPI app, powered by the Gradio Python Client!
Open up a terminal and navigate to the directory containing `main.py`. Then run the following command in the terminal:
```bash
$ uvicorn main:app
```
You should see an output that looks like this:
```csv
Loaded as API: https://abidla... | Step 4: Run your FastAPI app | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
1. `GRADIO_SERVER_PORT`
- **Description**: Specifies the port on which the Gradio app will run.
- **Default**: `7860`
- **Example**:
```bash
export GRADIO_SERVER_PORT=8000
```
2. `GRADIO_SERVER_NAME`
- **Description**: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, ... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
r the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).
- **Default**: `""`
- **Example**:
```sh
export GRADIO_ROOT_PATH="/myapp"
```
9. `GRADIO_SHARE`
- **Description**: Enables or disables sharing the Gradio app.
- **Default**: `"False... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
the application will trust the `X-Forwarded-For` header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the `gr.Request` [object's](https://www.gradio.app/docs/gradio/request) `client.host` property, it will correctly get the user's IP address ins... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e()`, `gr.ChatInterface()` or in `gr.Examples()`, Gradio will run your prediction function and save the results to disk. By default, this is in the `.gradio/cached_examples//` subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the enviro... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_RESET_EXAMPLES_CACHE="True"
```
20. `GRADIO_CHAT_FLAGGING_MODE`
- **Description**: Controls whether users can flag messages in `gr.ChatInterface` applications. Similar to `GRADIO_FLAGGING_MODE` but specifically for chat interfaces.
- **De... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
*Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_MCP_SERVER="True"
```
24. `GRADIO_NUM_WORKERS`
- **Description**: Number of multiple workers to launch in the background to offload traffic for file I/O and static assets from the main Gradio server. Only works when SSR mode is set.
- **Default... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
To set environment variables in your terminal, use the `export` command followed by the variable name and its value. For example:
```sh
export GRADIO_SERVER_PORT=8000
```
If you're using a `.env` file to manage your environment variables, you can add them like this:
```sh
GRADIO_SERVER_PORT=8000
GRADIO_SERVER_NAME="... | How to Set Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
**API endpoint names**
When you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the `api_name` parameter in `gr.Interface` or `gr.ChatInterface`. If you are using Gradio `Blocks`, you can name each event listener, like this:
```... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
**Adding API endpoints**
You can also add new API routes to your Gradio application that do not correspond to events in your UI.
For example, in this Gradio application, we add a new route that adds numbers and slices a list:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input = gr... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
This API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both [the Gradio Python client](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/).
... | The Clients | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Instead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the "API Recorder" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of... | The API Recorder 🪄 | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
The API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs.

... | MCP Server | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
You can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint `<your-gradio-app-url>/gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and underst... | OpenAPI Specification | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
By default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with "Home" as the title for the main page. You can customize the navbar behavior using the `gr.Navbar` component.
Per-Page Navbar Configuration
You can have different navbar configurations for each page of you... | Customizing the Navbar | https://gradio.app/guides/multipage-apps | Additional Features - Multipage Apps Guide |
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling).
Here's a basic example:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row() as row:
btn = gr.Button("Hide this row")
This function runs in the browser ... | When to Use Client Side Functions | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Client side functions have some important restrictions:
* They can only update component properties (not values)
* They cannot take any inputs
Here are some functions that will work with `js=True`:
```py
Simple property updates
lambda: gr.Textbox(lines=4)
Multiple component updates
lambda: [gr.Textbox(lines=4), gr.B... | Limitations | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Here's a more complete example showing how client side functions can improve the user experience:
$code_todo_list_js
| Complete Example | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
When you set `js=True`, Gradio:
1. Transpiles your Python function to JavaScript
2. Runs the function directly in the browser
3. Still sends the request to the server (for consistency and to handle any side effects)
This provides immediate visual feedback while ensuring your application state remains consistent.
| Behind the Scenes | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this:
```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
demo.launch(share=True) Share your demo with just 1 extra parame... | Sharing Demos | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free!
After you have [created a free Hugging Face account](https://huggingface.co/joi... | Hosting on HF Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can add a button to your Gradio app that creates a unique URL you can use to share your app and all components **as they currently are** with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time.
To add a de... | Sharing Deep Links | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Once you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
=> {
let v = obj.info.version;
content = document.querySelector('.prose');
content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v);
});
</script>
You can see examples of how web components look <a href="https://www.gradio.app">on the Gradio landing page</a>.
You can also customize the appe... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
ple of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.
```html
<gradio-app
space="gradio/Echocardiogram-Segmentation"
eager="true"
initial_height="0px"
></gradio-app>
```
Here's another example of how to use the `render` event. An event listener is used ... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a "Use via API" link.

This is a page that lists the endpoints t... | API Page | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function par... | Accessing the Network Request Directly | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
In some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo.
You can easily do this with `gradio.mount_gradio_app()`.
Here's a complete example:
$code_custom_path
Note that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in ... | Mounting Within Another FastAPI App | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Password-protected app
You may wish to put an authentication page in front of your app to limit who can open your app. With the `auth=` keyword argument in the `launch()` method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides pass... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Let's update the previous example to include a log out button:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as demo:
m = gr.Markdown()
logout_button = gr.Button("Logout", link="/logout")
demo.load(update_message, None, ... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
e. If you want
to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user
token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata
(see [documentation](https://huggingface.co/docs/hub/spaces-oauthsc... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.
OAuth (with external providers)
It is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app ([as discussed... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
entials on the [Google Developer Console](https://console.cloud.google.com/project)):
```python
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastAPI, Depends, Request
from starlette.config import Config
from starlette.responses import RedirectResponse
from starlette... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
r... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Gradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting `mcp_server=True` in the `.launch()` method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. ... | MCP Servers | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the `gr.Request` object [as discussed above](accessing-the-network-request-directly)) or, if they are logge... | Rate Limits | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information:
* What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)
* What input/output components are being used in the Gradio app
* Whether the... | Analytics | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
[Progressive Web Apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications.
Gradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `... | Progressive Web App (PWA) | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Let's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically.
$code_streaming_filter
$demo_streaming_filter
You will notice that if you change the filter value it will immediately take e... | A Realistic Image Demo | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream.
We can do so by just specifying the input image component as the output of the stream event.
$code_streaming_filter_unified... | Unified Image Demos | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
Your streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous `k` inputs to improve the accuracy of your transcription demo... | Keeping track of past inputs or outputs | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc). | End-to-End Examples | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
The simplest possible Workflow app:
```python
import gradio as gr
gr.Workflow().launch()
```
Open the app, drag Spaces and models from the sidebar onto the canvas, connect their ports, and hit **Run**. As you create nodes and edges, a `workflow.json` file will automatically be created in your working directory. You ... | Quickstart | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Pass your own Python functions via `bind=` and they appear as callable nodes on the canvas. Gradio inspects the function signature to auto-generate input/output ports.
```python
import gradio as gr
def summarize(text: str) -> str:
return text[:200]
gr.Workflow(bind=[summarize]).launch()
```
Use a dict to give n... | Binding Python functions | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
For pipelines you want to ship with a fixed topology, declare edges programmatically:
```python
import gradio as gr
def clean(text: str) -> str:
return text.strip().lower()
def tag(text: str) -> str:
return f"[processed] {text}"
gr.Workflow(
bind=[clean, tag],
edges=[("clean", "tag")],
).launch()
``... | Defining edges in code | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Pass a `graph=` path to load a saved workflow topology. The canvas reads from the file on each page load and autosaves back to it when you make edits.
```python
gr.Workflow(graph="workflow.json").launch()
```
If the file doesn't exist yet, it's created on first save. Combine `graph=` with `bind=` to pre-wire Space no... | Loading from a JSON file | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
A workflow is a JSON file with three node collections:
```json
{
"schema_version": "2",
"name": "My Pipeline",
"references": [
{
"id": "ref_image", "label": "Input Photo", "role": "reference",
"asset_type": "image",
"inputs": [{"id": "in", "label": "Image", "type": "image"}],
"output... | Workflow JSON format | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Ports are typed so the canvas can validate connections. Supported types:
`image` · `audio` · `video` · `text` · `number` · `boolean` · `gallery` · `file` · `json` · `model3d`
| Port types | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
One reference can feed multiple operators simultaneously — they run in parallel:
```python
workflow.json excerpt — one product photo → 4 FLUX Kontext branches
"edges": [
{"from_node_id": "ref_product", ..., "to_node_id": "op_kontext_0", ...},
{"from_node_id": "ref_product", ..., "to_node_id": "op_kontext_1", ...},... | Fan-out pipelines | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
A Workflow app is a standard Gradio app — deploy it to Hugging Face Spaces exactly like any other, by uploading the code to a Space, or by simply running in your terminal:
```
gradio deploy
```
On a Space, the canvas authenticates visitors via OAuth. The Space owner gets write access (can edit and save the workflow);... | Deploying to Spaces | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Every Workflow app is a Gradio app, meaning that it exposes a Gradio REST API endpoint for each output (subject) node. The endpoint name is derived from the subject's label — for example, a subject labelled "Output Image" becomes `/output_image`. Use `client.view_api()` to see the exact names for your workflow:
```pyt... | API access | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
By default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments:
- `concurrency_limit`: This sets the maximum number of concurrent executions for an event listener. By default, the limit is 1 unless configured otherwise in `Blocks.queue()`. You can also ... | Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
identified by `"gpu_queue"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.
Notes
- To ensure unlimited concurrency for an event listener, set `concurrency_limit=None`. This is useful if your function is calling e.g. an external API which handles the rate limiting... | Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.