Skip to content

Commit 5c8915b

Browse files
abidlabsgradio-pr-botaliabd
authored
Add cURL to view API Page and add a dedicated Guide (#8445)
* curl docs * add changeset * curl * guide complete * rename * more details * add changeset * add changeset * Update guides/08_gradio-clients-and-lite/03_querying-gradio-apps-with-curl.md Co-authored-by: Ali Abdalla <[email protected]> * Update guides/08_gradio-clients-and-lite/03_querying-gradio-apps-with-curl.md Co-authored-by: Ali Abdalla <[email protected]> * changes * add support for curl in view api docs * add support for files * format frontend * lint * Update js/app/src/api_docs/img/bash.svg Co-authored-by: Ali Abdalla <[email protected]> * remove api recorder on bash * fixes * changes * fix --------- Co-authored-by: gradio-pr-bot <[email protected]> Co-authored-by: Ali Abdalla <[email protected]>
1 parent 2cd02ff commit 5c8915b

14 files changed

+429
-50
lines changed

.changeset/ripe-tires-nail.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@gradio/app": patch
3+
"gradio": patch
4+
---
5+
6+
feat:Add cURL to view API Page and add a dedicated Guide

.config/.prettierignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,5 @@ sweep.yaml
2929
**/src/lib/json/**/*
3030
**/playwright/.cache/**/*
3131
**/theme/src/pollen.css
32-
**/venv/**
32+
**/venv/**
33+
../js/app/src/api_docs/CodeSnippet.svelte

gradio/routes.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -768,7 +768,9 @@ async def simple_predict_post(
768768
request: fastapi.Request,
769769
username: str = Depends(get_current_user),
770770
):
771-
full_body = PredictBody(**body.model_dump(), simple_format=True)
771+
full_body = PredictBody(
772+
**body.model_dump(), request=request, simple_format=True
773+
)
772774
fn = route_utils.get_fn(
773775
blocks=app.get_blocks(), api_name=api_name, body=full_body
774776
)
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
# Querying Gradio Apps with Curl
2+
3+
Tags: CURL, API, SPACES
4+
5+
It is possible to use any Gradio app as an API using cURL, the command-line tool that is pre-installed on many operating systems. This is particularly useful if you are trying to query a Gradio app from an environment other than Python or Javascript (since specialized Gradio clients exist for both [Python](/guides/getting-started-with-the-python-client) and [Javascript](/guides/getting-started-with-the-js-client)).
6+
7+
As an example, consider this Gradio demo that translates text from English to French: https://abidlabs-en2fr.hf.space/.
8+
9+
Using `curl`, we can translate text programmatically.
10+
11+
Here's the code to do it:
12+
13+
```bash
14+
$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H "Content-Type: application/json" -d '{
15+
"data": ["Hello, my friend."]
16+
}'
17+
18+
> {"event_id": $EVENT_ID}
19+
```
20+
21+
```bash
22+
$ curl -N https://abidlabs-en2fr.hf.space/call/predict/$EVENT_ID
23+
24+
> event: complete
25+
> data: ["Bonjour, mon ami."]
26+
```
27+
28+
29+
Tip: making a prediction and getting a result requires two `curl` requests: a `POST` and a `GET`. The `POST` request returns an `EVENT_ID` and prints it to the console , which is used in the second `GET` request to fetch the results. We'll cover these two steps in more detail in the Guide below.
30+
31+
32+
**Prerequisites**: For this Guide, you do _not_ need to know the `gradio` library in great detail. However, it is helpful to have general familiarity with Gradio's concepts of input and output components.
33+
34+
## Installation
35+
36+
You generally don't need to install cURL, as it comes pre-installed on many operating systems. Run:
37+
38+
```bash
39+
curl --version
40+
```
41+
42+
to confirm that `curl` is installed. If it is not already installed, you can install it by visiting https://curl.se/download.html.
43+
44+
45+
## Step 0: Get the URL for your Gradio App
46+
47+
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
48+
49+
50+
**Hugging Face Spaces**
51+
52+
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 URL of the Space webpage. For example:
53+
54+
```bash
55+
❌ Space URL: https://huggingface.co/spaces/abidlabs/en2fr
56+
✅ Gradio app URL: https://abidlabs-en2fr.hf.space/
57+
```
58+
59+
You can get the Gradio app URL by clicking the "view API" link at the bottom of the page. Or, you can right-click on the page and then click on "View Frame Source" or the equivalent in your browser to view the URL of the embedded Gradio app.
60+
61+
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,
62+
and then use it to make as many requests as you'd like!
63+
64+
Note: to query private Spaces, you will need to pass in your Hugging Face (HF) token. You can get your HF token here: https://huggingface.co/settings/tokens. In this case, you will need to include an additional header in both of your `curl` calls that we'll discuss below:
65+
66+
```bash
67+
-H "Authorization: Bearer $HF_TOKEN"
68+
```
69+
70+
Now, we are ready to make the two `curl` requests.
71+
72+
## Step 1: Make a Prediction (POST)
73+
74+
The first of the two `curl` requests is `POST` request that submits the input payload to the Gradio app.
75+
76+
The syntax of the `POST` request is as follows:
77+
78+
```bash
79+
$ curl -X POST $URL/call/$API_NAME -H "Content-Type: application/json" -d '{
80+
"data": $PAYLOAD
81+
}'
82+
```
83+
84+
Here:
85+
86+
* `$URL` is the URL of the Gradio app as obtained in Step 0
87+
* `$API_NAME` is the name of the API endpoint for the event that you are running. You can get the API endpoint names by clicking the "view API" link at the bottom of the page.
88+
* `$PAYLOAD` is a valid JSON data list containing the input payload, one element for each input component.
89+
90+
When you make this `POST` request successfully, you will get an event id that is printed to the terminal in this format:
91+
92+
```bash
93+
> {"event_id": $EVENT_ID}
94+
```
95+
96+
This `EVENT_ID` will be needed in the subsequent `curl` request to fetch the results of the prediction.
97+
98+
Here are some examples of how to make the `POST` request
99+
100+
**Basic Example**
101+
102+
Revisiting the example at the beginning of the page, here is how to make the `POST` request for a simple Gradio application that takes in a single input text component:
103+
104+
```bash
105+
$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H "Content-Type: application/json" -d '{
106+
"data": ["Hello, my friend."]
107+
}'
108+
```
109+
110+
**Multiple Input Components**
111+
112+
This [Gradio demo](https://huggingface.co/spaces/gradio/hello_world_3) accepts three inputs: a string corresponding to the `gr.Textbox`, a boolean value corresponding to the `gr.Checkbox`, and a numerical value corresponding to the `gr.Slider`. Here is the `POST` request:
113+
114+
```bash
115+
curl -X POST https://gradio-hello-world-3.hf.space/call/predict -H "Content-Type: application/json" -d '{
116+
"data": ["Hello", true, 5]
117+
}'
118+
```
119+
120+
**Private Spaces**
121+
122+
As mentioned earlier, if you are making 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:
123+
124+
```bash
125+
$ curl -X POST https://private-space.hf.space/call/predict -H "Content-Type: application/json" -H "Authorization: Bearer $HF_TOKEN" -d '{
126+
"data": ["Hello, my friend."]
127+
}'
128+
```
129+
130+
**Files**
131+
132+
If your Gradio application requires file inputs, you can pass in files as URLs through `curl`. The URL needs to be enclosed in a dictionary in this format:
133+
134+
```bash
135+
{"path": $URL}
136+
```
137+
138+
Here is an example `POST` request:
139+
140+
```bash
141+
$ curl -X POST https://gradio-image-mod.hf.space/call/predict -H "Content-Type: application/json" -d '{
142+
"data": [{"path": "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"}]
143+
}'
144+
```
145+
146+
147+
**Stateful Demos**
148+
149+
If your Gradio demo [persists user state](/guides/interface-state) across multiple interactions (e.g. is a chatbot), you can pass in a `session_hash` alongside the `data`. Requests with the same `session_hash` are assumed to be part of the same user session. Here's how that might look:
150+
151+
```bash
152+
# These two requests will share a session
153+
154+
curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{
155+
"data": ["Are you sentient?"],
156+
"session_hash": "randomsequence1234"
157+
}'
158+
159+
curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{
160+
"data": ["Really?"],
161+
"session_hash": "randomsequence1234"
162+
}'
163+
164+
# This request will be treated as a new session
165+
166+
curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{
167+
"data": ["Are you sentient?"],
168+
"session_hash": "newsequence5678"
169+
}'
170+
```
171+
172+
173+
174+
## Step 2: GET the result
175+
176+
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).
177+
178+
To stream the results for your prediction, make a `GET` request with the following syntax:
179+
180+
```bash
181+
$ curl -N $URL/call/$API_NAME/$EVENT_ID
182+
```
183+
184+
185+
Tip: If you are fetching results from a private Space, include a header with your HF token like this: `-H "Authorization: Bearer $HF_TOKEN"` in the `GET` request.
186+
187+
This should produce a stream of responses in this format:
188+
189+
```bash
190+
event: ...
191+
data: ...
192+
event: ...
193+
data: ...
194+
...
195+
```
196+
197+
Here: `event` can be one of the following:
198+
* `generating`: indicating an intermediate result
199+
* `complete`: indicating that the prediction is complete and the final result
200+
* `error`: indicating that the prediction was not completed successfully
201+
* `heartbeat`: sent every 15 seconds to keep the request alive
202+
203+
The `data` is in the same format as the input payload: valid JSON data list containing the output result, one element for each output component.
204+
205+
Here are some examples of what results you should expect if a request is completed successfully:
206+
207+
**Basic Example**
208+
209+
Revisiting the example at the beginning of the page, we would expect the result to look like this:
210+
211+
```bash
212+
event: complete
213+
data: ["Bonjour, mon ami."]
214+
```
215+
216+
**Multiple Outputs**
217+
218+
If your endpoint returns multiple values, they will appear as elements of the `data` list:
219+
220+
```bash
221+
event: complete
222+
data: ["Good morning Hello. It is 5 degrees today", -15.0]
223+
```
224+
225+
**Streaming Example**
226+
227+
If your Gradio app [streams a sequence of values](/guides/streaming-outputs), then they will be streamed directly to your terminal, like this:
228+
229+
```bash
230+
event: generating
231+
data: ["Hello, w!"]
232+
event: generating
233+
data: ["Hello, wo!"]
234+
event: generating
235+
data: ["Hello, wor!"]
236+
event: generating
237+
data: ["Hello, worl!"]
238+
event: generating
239+
data: ["Hello, world!"]
240+
event: complete
241+
data: ["Hello, world!"]
242+
```
243+
244+
**File Example**
245+
246+
If your Gradio app returns a file, the file will be represented as a dictionary in this format (including potentially some additional keys):
247+
248+
```python
249+
{
250+
"orig_name": "example.jpg",
251+
"path": "/path/in/server.jpg",
252+
"url": "https:/example.com/example.jpg",
253+
"meta": {"_type": "gradio.FileData"}
254+
}
255+
```
256+
257+
In your terminal, it may appear like this:
258+
259+
```bash
260+
event: complete
261+
data: [{"path": "/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp", "url": "https://gradio-image-mod.hf.space/c/file=/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp", "size": null, "orig_name": "image.webp", "mime_type": null, "is_stream": false, "meta": {"_type": "gradio.FileData"}}]
262+
```
File renamed without changes.

js/app/src/api_docs/ApiBanner.svelte

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
export let root: string;
88
export let api_count: number;
9+
export let current_language: "python" | "javascript" | "bash";
910
1011
const dispatch = createEventDispatcher();
1112
</script>
@@ -21,13 +22,15 @@
2122
<span class="counts">
2223
<span class="url">{api_count}</span> API endpoint{#if api_count > 1}s{/if}<br
2324
/>
24-
<Button
25-
size="sm"
26-
variant="primary"
27-
on:click={() => dispatch("close", { api_recorder_visible: true })}
28-
>
29-
🪄 API Recorder
30-
</Button>
25+
{#if current_language !== "bash"}
26+
<Button
27+
size="sm"
28+
variant="primary"
29+
on:click={() => dispatch("close", { api_recorder_visible: true })}
30+
>
31+
🪄 API Recorder
32+
</Button>
33+
{/if}
3134
</span>
3235
</h2>
3336

0 commit comments

Comments
 (0)