Chapter 22. API and OpenAPI
The work of the previous twenty-one chapters all lives on one page. The components are laid out, the events bound, the host wired up; a person clicks a button, the handler function runs, and the result comes back into the components. These handler functions must also be able to run without anyone clicking a button.
Every button with a handler function bound to it is also an HTTP endpoint. No extra declaration, no separate controller: once the page is written, the API is already there. What is left to decide is what this API is called, how others know it exists, and which APIs should not be known to others.
Names come from bindings, two documents answer different questions, and calls split into two routes, direct and job-style. At the end of the chapter a client on the same machine walks the whole path, and along the way checks exactly what visibility does and does not control.
First look at what this chapter adds to the workbench. The sample gains one page, “API”, at the address /api.
Figure 22-1 The API page: the “Clean up” button on the left can be called by a script, while the “Streaming” button on the right shows its process only through a job-style call
Every button on the page is one binding, that is, one API. The binding for the “Clean up” button on the left looks like this.
run.Click(ArrangeForApi, [text, width], [body, stats],
apiName: "API Clean up",
apiDescription: "Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)");
The only difference from the previous twenty chapters is one more apiDescription. apiName was already used in Chapter 5 and apiVisibility in Chapter 20; this chapter explains those two parameters fully, then adds the two things never mentioned before: the description and the parameter names.
The boundary first, clearly: this chapter is about “how it gets called”. The authentication door still works as in Chapter 20; this chapter mentions it only when it needs to tell “the door” apart from “the curtain”.
22.1 Rules for Deriving API Names
Every binding with a handler function has a name whether you want one or not. If you want one, it is the one you gave; if you do not, the framework generates one for you. There are only four generation rules, and once you know them you can predict what your API will be called.
Figure 22-2 The four sources of a name, and the suffix when names collide
First. If apiName is given, use what was given, as-is, with no processing. Letters and digits are fine, non-ASCII letters are also accepted, spaces are fine, starting with a digit is fine too.
Second. If it is not given but the handler function is a named method, use the method name. Write Click(Handlers.CleanText, …) and the API is called CleanText, matching the C# method name.
Third. If it is not given and the handler function is a lambda or an anonymous method, it is called lambda. The name the compiler generates for such a method is not a valid identifier, so the framework does not guess and writes lambda uniformly. From the second one on, a numeric suffix is added: lambda_1, lambda_2.
Fourth. If there is only front-end script and no handler function, it is called js_fn; if there is neither, it is called unnamed. Both of these are private. With no handler function and no name given by anyone, there is no reason for it to become an API.
You do not need a separate experiment for these four: a pair sits at the bottom of the sample’s “API” page. Neither button is given a name; the left one binds ApiDesk.CharacterSummary, so the API is called CharacterSummary; the right one binds a lambda, so the API is called lambda_1.
Why lambda_1 and not lambda? Because the name lambda is already taken. The “Copy link with state” button on the “Text” page also has an unnamed binding inside it; it got lambda first, and it is itself Undocumented (one of the three undocumented names in 22.3 is it). That is where the suffix comes from. The suffix is not added only for a duplicate name; it is added as soon as the name is taken, and the order in which names are taken is the order in which the page is written.
Local functions keep their names too. Write the handler function as string CharacterSummary(string text) => … directly in Program.cs and the API name is CharacterSummary. The method name the compiler generates for it is <<Main>$>g__CharacterSummary|0_0; the original name is still there between g__ and |, and the framework can read it out. Lambdas and anonymous methods have no such segment, which is why they are all called lambda. So “named method” means whether the way you write it has a name, not that it has to be moved into a class.
The other two derived names are in the sample too. js_fn comes from the purely front-end binding inside that share button, and unnamed and unnamed_1 come from the bindings inside the two cancel buttons on the “Run” page. Neither kind is a handler function you wrote, both are private, and they do not enter the list.
The same /config also shows the distribution: of 120 bindings, 110 are public, 3 are undocumented, and 7 are private. These numbers come up again later. The 110 names in the API list are exactly these 110 public bindings.
Names you give yourself work the same way. Write apiName: "Duplicate" on two bindings and the second one’s API name becomes Duplicate_1. Add two yourself and you will see it. This rule has a direct consequence. Renaming an existing API can quietly change another one. When two names collide, the second gets a suffix, while the caller is still calling by the original name, and the 404 it gets is exactly the same as “name misspelled”. So either name things systematically, or read through the list after every change.
The same name is written differently in two places; this is the easiest one to trip over.
- In
/config,api_nameisClean up, with no leading slash; - In
/gradio_api/info, the key is/Clean up, with a leading slash; - In a URL it is one segment of the path,
/gradio_api/call/Clean up.
The leading slash is “the key of this one list”, not a path separator. When the client assembles a URL, do not add another slash: /gradio_api/call//Clean up is a different path and the route will not match.
What characters a name can hold turns out, in testing, to be broader than you would think and narrower than you would think.
- Letters and digits are fine; non-ASCII letters are also accepted.
curlpercent-encodes the name and the call works. - Spaces are fine, but they must be encoded as
%20; unencoded, the request line is invalid. - Slashes are not. Write a name as
With/Slashand/gradio_api/call/With%2FSlashreturns 404, saying “cannot recognize this name”; put the slash into the URL as-is and the route treats it as two segments and returns 405. In other words, a name with a slash cannot be called from the moment it is generated, yet it is still listed in/info.
So the naming rule collapses into one sentence. Use letters and digits; non-ASCII letters are also accepted, slashes are not. For a sense of hierarchy, use a prefix like Text cleanup, not text/Clean up.
One more thing is tied to the name: the name is the object of visibility. Chapter 20 said that Private means “this name is neither shown nor recognized”. With no name, showing or not showing is meaningless, so unnamed is necessarily private. That is a rule hard-coded in the framework. Conversely, as soon as you give a name, it is public by default, even if the binding is only an intermediate step on the page. The default chooses “public” over “private” because the authors of most bindings never thought about APIs at all; that default is friendly to teaching and unfriendly to security, so the Chapter 20 advice to “set intermediate steps to Private” is not fussiness.
22.2 API Descriptions and Parameter Names
The name settles “what it is called”; next is “how to use it”. After a caller gets a name, it needs to know two things: what this API does, and what each of those parameters is.
The sample’s binding is this line.
run.Click(ArrangeForApi, [text, width], [body, stats],
apiName: "API Clean up",
apiDescription: "Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)");
apiDescription is the API’s own description. It appears in the description field of /gradio_api/info and also becomes the summary of that operation in OpenAPI.
The binding has one more parameter of the same kind, endpointDescription. The name is very similar, but the effect is smaller than it looks. Try two sets of temporary bindings, one each way. Write only apiDescription and OpenAPI’s summary is that description; write only endpointDescription and the summary is it too; write both and only apiDescription appears, with not a single character of endpointDescription showing. So it is a substitute that steps in when apiDescription is not written. It neither stacks nor overrides. The sample does not write it, because there is no reason to write the same thing twice.
OpenAPI’s description is longer than the summary because the framework appends a stretch of automatically generated English after it.
Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)
Output must be fetched from GET /gradio_api/call/API Clean up/{event_id}.
Returns an array of 1 elements of the following format: ["output ({'type': 'string'})"]
The first line is yours; the second and third are what it added. The added part explains two things: that the result has to be fetched with a separate request, and how many elements the returned array has and what type each is. The description of that GET operation also says “the final event is event: complete”, and the last thing written into the stream is exactly it, with the complete output array in data (22.5 looks at the whole stream). Write the client following that sentence; there is no need to guess which events this stream has.
Parameter names are another thing that goes against intuition. They are not called text and width; they are called param_0 and param_1.
C# method parameters have names, but the API’s parameter names do not come from there. In /info, each parameter looks like this.
{
"label": "Source text",
"parameter_name": "param_0",
"parameter_has_default": true,
"parameter_default": "Wrapping looks simple,",
"type": { "type": "string" },
"component": "Textbox"
}
label is the component’s label, parameter_name is the positional name, and parameter_default is the component’s value at this moment. The three fields each say their own thing, but they are easily misread as one meaning. parameter_has_default says “this component currently has a value”. As soon as something is filled into the component, it is true. The real default-value semantics is the one from Chapter 3: a parameter that is not supplied gets the type’s default value.
Two requests make this clear. Send an empty array to API Clean up, then read the result stream by the event_id you get back.
POST /gradio_api/call/API Clean up {"data": []}
GET /gradio_api/call/API Clean up/{event_id}
→ event: complete
data: ["/", "0 lines, 0 characters, longest line 0 characters"]
Neither parameter is supplied; the first gets an empty string, the second gets null, the handler function runs anyway, and the result is "/", from the interpolated $"{t}/{w}". Supplying one extra is fine too: the 9 in {"data":["a",3,9]} is dropped and the result is still "a/3". These two behaviors match the component contract from Chapter 3 exactly, just through a different entry point.
Since parameter names are positional names, the description has to spell out the order. The sample’s description deliberately writes “param_0 is the source text, param_1 is the characters per line”, because someone reading the document sees only param_0. This is not empty courtesy. For an API with only param_0, that sentence is the one thing the caller can rely on.
The same holds on the return side: returns has only label, type, and component, no name. Two return values are two positions in the array, with the order set by outputs. So the phrase “return the body and statistics” is something you have to write into the description yourself.
22.3 API Info and the OpenAPI Description
The name and the description both live on the binding; next you read them out. There are two addresses, both behind authentication, both read-only.
Figure 22-3 The two documents answer two questions: what names there are, and how to send a request
The first is GET /gradio_api/info. Its top level has only two keys, named_endpoints and unnamed_endpoints. The former is a mapping from names to descriptions, the latter is basically empty. Because every binding gets a name, even unnamed is a name. So the only one you can actually read is the first.
In the sample app it has 110 names and the whole JSON is around 450 KB. The bulk is the four ready-made call snippets under each name: Python, JavaScript, bash, CLI. The bash one is the most useful; it gives you a command you can paste straight into a terminal.
curl -X POST http://127.0.0.1:7860/gradio_api/run/API Clean up -s -H "Content-Type: application/json" \
-d '{"data": ["Wrapping looks simple...", 12]}'
Note that it uses /gradio_api/run/, the direct-call route (22.4). The list itself does not say what distinguishes this route from the job-style one; you have to know that yourself.
The values in data are the component’s current values, not “example values”. The sample’s text box holds a whole paragraph, and the snippet carries that paragraph along verbatim. So it is a starting point for copying, not a finished product you can run as-is. Replace the first parameter before pasting.
/info supports one query parameter, ?all_endpoints=true. With it, Undocumented names are listed too; without it, only Public. In the sample the default is 110, and with the parameter 113; the three in between are the bindings marked Undocumented. Private does not appear in either case.
The second is GET /gradio_api/openapi.json, a standard OpenAPI 3.0.2 document. Its info section comes from the app itself.
{
"title": "Personal Local Workbench",
"description": "The public API of the Personal Local Workbench: one cleanup, one streaming, and three visibility levels.",
"version": "xxx"
}
The title is the one from gr.Blocks(title: …); the description is demo.Description. That property exists for OpenAPI, so /info does not have it; the version on the last line comes from the upstream protocol, not the one in PackageReference.
The paths section is the important part: each name takes three paths.
/gradio_api/call/API Clean up POST submit, returns event_id
/gradio_api/call/v2/API Clean up POST another path for the same call
/gradio_api/call/API Clean up/{event_id} GET fetch the result by number, SSE
The sample has 110 names and 331 paths. 110 times 3 plus one upload matches exactly. operationId is the name, and the GET one is “the name plus _get”; summary is apiDescription; and the property names of requestBody are param_0, param_1.
Two omissions matter, because they mislead people writing code against the document.
First, OpenAPI has no /gradio_api/run/{name}. Direct calls really do work, and the bash snippet in /info uses exactly that, but it is not in OpenAPI. The document describes only the job-style route.
Second, OpenAPI has no security scheme. The sample has authentication on; an unauthenticated request to /gradio_api/openapi.json returns 401, yet the document you get after logging in has no securitySchemes anywhere. Only the /gradio_api/upload path says security: [{"login_check": []}], and the login_check scheme is not defined at all. In other words, the document cannot be used to decide “does this API require login”. To decide that, look at whether it is behind the door. What Chapter 20 said still holds here.
Both documents can be read once on the page. The sample’s “API” page has two buttons, and they read exactly this same data.
string ReadInfo()
{
var named = demo.GetApiInfo("/", "/", false)["named_endpoints"]!.AsObject();
// ...one line per name: name, visibility, parameter count, description
}
string ReadOpenApi()
{
var document = demo.GetOpenApiDocument("/");
var paths = document["paths"]!.AsObject();
// ...count paths, count names
}
Blocks.GetApiInfo and Blocks.GetOpenApiDocument are what happens behind those two HTTP addresses. Reading them on the page has one benefit: you can see at once that “the document is a mirror of the bindings”. Change one binding, refresh the list, and it changes. Both buttons are themselves private, because “reading the document” should not turn into yet another API.
Figure 22-4 The list is a mirror of the bindings: 110 names, each with visibility, parameter count, and description
The two documents can divide the work: use /info to find names, count parameters, and copy snippets; use OpenAPI to generate clients and plug into code tools. The former is for people to read, the latter for machines. Using them the other way round feels awkward. OpenAPI has no “take it all in at a glance” name list, and /info has no structural definition of the request body.
A 450 KB JSON is not something to read with your eyes. When you only want the names, filter it.
curl -s -b cookies.txt http://127.0.0.1:7860/gradio_api/info \
| jq -r '.named_endpoints | to_entries[] | "\(.key)\t\(.value.api_visibility)\t\(.value.parameters | length)"'
One name per line, followed by visibility and parameter count. The code_snippets section takes up the most space; filter it out and the whole document is only a few kilobytes, much easier to read. This is a habit worth building. Once there are many APIs, “is this name actually there” is a question you ask every day, and answering it by flipping through the page is too slow.
22.4 Direct Calls and Job-Style Calls
The same handler function has two call paths with the same parameters; the difference is “who waits for you”.
Figure 22-5 Two routes: one connection waits for the run to finish, the other submits a job and takes a number
A direct call is one request.
POST /gradio_api/run/API Clean up
{"data": ["Wrapping text...", 12]}
→ 200
{"data": ["Wrapping loo\n...", "12 lines, 109 characters, longest line 12 characters"],
"is_generating": false, "duration": 0.0065, …}
The request goes out, the connection hangs there, the handler function finishes, and the body is the result. No number, no intermediate state, and nowhere else to check how this run went.
A job-style call is two requests.
POST /gradio_api/call/API Clean up
{"data": ["Wrapping text...", 12]}
→ 200 {"event_id": "0367afaa297045b58a4506f35a1e2b5f"}
Once you have the number, send a separate GET /gradio_api/call/API Clean up/0367afaa…; the server treats this connection as a stream and writes it down frame by frame until the run ends. The number identifies this run and has nothing to do with the page. When the same handler function is clicked once on the page, it goes through this same queue too, only the number is not shown to you.
There are four differences, each one tested for real.
One: direct calls do not go through the queue. The three “A1”, “A2”, “A3” buttons on the sample’s “Run” page have a concurrency limit of 1, and after every run they log a line “how many were running on entry”. Send two /run at the same time: A1 enters at 21:38:48.182, A2 at 21:38:48.598, and the second one’s record says “2 running on entry, peak 2”. The limit did not stop it. Switch to two /call: A1 enters at 00.854 and leaves at 02.847, A2 only enters at 02.921, and both say “1 running on entry”. So the concurrency limit, queue limit, and queue rejection from Chapter 15 have no effect at all on /run.
Two: for a streaming handler function, a direct call delivers only the first frame. For the same streaming API, the body /run returns has is_generating set to true and data holding the first frame, and then the connection closes. Where do the remaining frames go? Nowhere; they are dropped. To see the process you can only use a job-style call.
Three: a job-style call sends you the process frame by frame. The result stream writes intermediate values out one frame at a time and closes with an event: complete; /run has only the body after the run finishes. Messages like queue position, run starting, and progress are on the /queue/data the page reads, not in the result stream — the result stream delivers only outputs.
Four: failures look different. /run fails with a 500 and a body of {"error": …}; the submit step of /call still returns 200, and the failure shows up in the result stream as an event: error plus a data (see 22.5 for details).
/call/v2/name exists too: the submit and retrieve formats are identical to v1, run both once and there is no difference in the frames returned. The document lists both, and in practice either works; this book’s sample uses v1 because it matches what the /info snippet writes.
Which to choose depends on whether this call needs the process.
- Only need the result and it runs fast?
/run. One line ofcurl, the least work in a script. - Need the process, or it may run a long time?
/call. One more request buys you a stream you can read. - A streaming handler function can only use
/call;/rungives you just the first frame.
One more, less obvious. /run “not going through the queue” also means it is not managed by cancellation. The cancel button in Chapter 17 cancels runs in the queue; /run is not in the queue, so it cannot be cancelled. With one person on a local machine this is no problem; when a script calls in bulk, a runaway /run can only be waited out until it ends on its own.
22.5 Consuming Streaming Results
The stream a job-style call gets is the one that most needs explaining. It is named SSE events, a different kind of frame from the queue stream the page reads.
First look at a real stream. The sample’s streaming API sends the wrapped body out line by line, eight lines, three hundred and fifty milliseconds apart.
event: generating
data: ["Wrapping loo"]
event: generating
data: [[["append",[],"\nks simple,"]]]
event: complete
data: ["Wrapping text...\nSkip all bla"]
The first thing to remember: the event name is on the event: line, and data holds only outputs. The description of the GET operation in OpenAPI says “the final event is event: complete”, and the last thing written into the stream is exactly it. Read it by the SSE standard. One event: line says what this frame is, one data: line gives the content, with a blank line separating them.
A stream that finishes normally has only three kinds of events, each in its own place.
generating, an intermediate frame;datais the output array for that frame.complete. The run is done;datais the complete output array, and then the connection ends.heartbeat. Inserted when the connection has been idle long enough;dataisnulland does not mean there is a result.
When the run fails, or the number cannot be read, it is event: error, with the reason in data. Queue messages like queue position, run starting, progress, logs, and close_stream are not written into this stream. They belong to the /queue/data the page reads; what a job-style call gets is output that has already been picked clean.
The second thing, and the easiest to trip over: an intermediate frame is not necessarily a complete value.
The first frame is complete. The first element of the data array is “Wrapping loo”. Starting with the second frame, the first element of data holds a patch.
[[["append", [], "\nks simple,"]]]
Take it apart layer by layer. The outermost is an array whose length equals the number of output components; this layer holds patch operations; each operation has three elements: operation name, path, value. There are only two operation names, append to append and replace to replace. The paths are all empty arrays, because patches work on the whole value, not on fields.
The last complete frame goes back to a complete value, and it matches the result assembled from the last generating frame. So there are two ways to consume it, each with its own cost.
Only want the final result. Stop at complete and ignore every earlier frame. Simple, but then you cannot see the process.
Want to show the process. You have to maintain a “value so far” yourself: assign the first frame directly, then stack each patch onto it in every later frame. The sample’s client does exactly this, and its log looks like this.
Frame 1 full (generating) 12 characters, tail "Wrapping loo"
Frame 2 patch append "⏎ks simple," -> total 23 characters
Frame 3 patch append "⏎but first se" -> total 36 characters
...
Frame 8 patch append "⏎Skip all bla" -> total 98 characters
Frame 9 full (complete) 98 characters, tail "…⏎Skip all bla"
The accumulated numbers are computed by the client itself; the server only sends changes. This design is friendly to bandwidth and unfriendly to the client. The “each frame delivers everything up to now” from Chapter 16 is the semantics on the handler function side; before sending to the client, the server compresses it into a diff again. Do not mix the two up.
There are only two kinds of patch, append and replace. Any change can be written as “replace the whole value”, only then no bandwidth is saved. When you hit an operation name you do not recognize, the safest move is to fall back to the complete value in the last frame. complete always gives the complete result; it will not lie to you.
One more boundary, more important than it looks: a stream has only one reader. The first GET claims it; read the same number again and you get a 200 plus one event: error frame.
event: error
data: "404: Not Found"
Note the status code is 200. The error hides in the stream, not in the HTTP status. This is the most easily overlooked rule when reading this stream. A successful GET request does not mean the run succeeded; success or failure depends on the event name — complete is success, error is failure. When the number cannot be read, data is a reason (such as "404: Not Found"); when the run fails, data is an output object describing the failure.
The consequence of the single-reader limit is practical: a dropped connection cannot be recovered by reconnecting. Once the connection breaks, no one picks up the remaining frames of this run, and a fresh GET gets only that 404 frame. When writing the client, put the stream read somewhere it will not be interrupted. Read it through in one go; if you really need to start over, you can only submit again, which means running the handler function once more. Long tasks especially need watching. Better to set a long timeout than to count on reconnecting after a break.
22.6 Calling from a Client on the Same Machine
The previous sections were all curl, enough to see the protocol but not enough to write into a program. This section writes the whole path as a client: log in, read the documents, make both kinds of call, and separate the errors. It runs outside the same process, uses HttpClient, and does not reference Gradio.NET. The API’s contract is those two HTTP documents, not some set of types.
public sealed class ApiClient : IDisposable
{
private readonly HttpClient _http;
private readonly HttpClient _stream;
public ApiClient(string baseAddress)
{
var cookies = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookies,
UseCookies = true,
};
// Normal requests: thirty seconds is the upper limit. Both clients share the same handler, so the cookies are the same.
_http = new HttpClient(handler, disposeHandler: false)
{
BaseAddress = new Uri(baseAddress),
Timeout = TimeSpan.FromSeconds(30),
};
// Reading streams: no timeout is set. The timeout is decided by the token from the caller, otherwise a long stream would be cut off by the client itself.
_stream = new HttpClient(handler, disposeHandler: false)
{
BaseAddress = new Uri(baseAddress),
Timeout = Timeout.InfiniteTimeSpan,
};
}
CookieContainer hangs off HttpClientHandler, not off HttpClient. So you go through a handler, and the two clients share it. Splitting into two clients is for one thing only. HttpClient.Timeout governs the whole request, including the stream-reading part, so a thirty-second timeout would cut off a long stream, and by the single-reader rule in 22.5, once cut off it cannot be reconnected. The stream-reading client sets no timeout; when to give up is decided by CancellationToken.
CookieContainer is required. Authentication relies on cookies; Chapter 20 said the browser holds two cookies after login, and the client has to save them itself or the second request returns 401.
Login is form-encoded, not JSON.
public async Task<int> LoginAsync(string user, string password)
{
using var body = new FormUrlEncodedContent(new Dictionary<string, string>
{
["username"] = user,
["password"] = password,
});
using var response = await _http.PostAsync("login", body);
return (int)response.StatusCode;
}
Submitting this step as JSON returns 422. The authentication layer only accepts form data. This is not a big deal, but almost everyone hits it the first time they write a client, because every other API is JSON.
The two steps of a job-style call are, in the client, two methods, “submit” and “read stream”. The read-stream one is the only place in the whole stretch of code that needs care.
public sealed record StreamFrame(string Event, JsonNode? Data);
public async IAsyncEnumerable<StreamFrame> StreamAsync(
string name,
string eventId,
[EnumeratorCancellation] CancellationToken token = default)
{
var url = $"gradio_api/call/{Uri.EscapeDataString(name)}/{eventId}";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await _stream.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
if (!response.IsSuccessStatusCode)
{
yield return new StreamFrame("http_error", JsonValue.Create((int)response.StatusCode));
yield break;
}
await using var stream = await response.Content.ReadAsStreamAsync(token);
using var reader = new StreamReader(stream);
// Reading null means the stream is over. Do not use EndOfStream: it waits synchronously for one read, which is exactly what blocks streaming.
string? pendingEvent = null;
while (await reader.ReadLineAsync(token) is { } line)
{
if (line.StartsWith("event: ", StringComparison.Ordinal))
{
pendingEvent = line["event: ".Length..].Trim();
}
else if (line.StartsWith("data: ", StringComparison.Ordinal))
{
pendingEvent ??= "message";
yield return new StreamFrame(pendingEvent, JsonNode.Parse(line["data: ".Length..]));
pendingEvent = null;
}
}
}
Three details decide whether this is usable. [EnumeratorCancellation] makes that token actually get into the iterator. The long task in Chapter 21 uses the same pattern; without the attribute, the token passed in and the iterator’s own token are not the same one. HttpCompletionOption.ResponseHeadersRead makes SendAsync return as soon as the response headers arrive, without waiting for the body to end. Without this parameter, SendAsync waits until the stream closes, which is the same as degrading streaming into a one-shot. Reading line by line and pairing the event: line with the data: line is because the blank line is the frame separator and one event is made of those two lines. Read the type first, then the output; the other lines carry no information. The while (await reader.ReadLineAsync(token) is { } line) pattern is not a matter of style either. StreamReader.EndOfStream waits synchronously for one read, and inside an async loop that is exactly what blocks streaming.
The name needs Uri.EscapeDataString. Leave a name with spaces or non-ASCII letters unencoded and Kestrel returns 400 before routing, with an empty body. The reason is that the request line itself is invalid, nothing to do with authentication.
Stacking the patches is these few lines in the client.
static JsonNode? Patch(JsonNode? current, JsonArray patch)
{
foreach (var node in patch)
{
var op = node!.AsArray();
var kind = op[0]!.GetValue<string>();
var value = op[2]?.DeepClone();
current = kind switch
{
"append" => JsonValue.Create((current?.GetValue<string>() ?? "") + value?.GetValue<string>()),
_ => value,
};
}
return current;
}
The _ => value branch catches replace and every operation name never seen before. Written this way it means: recognize append and you save one assignment; do not recognize it and you replace the whole value. The worst case degrades into “every frame is a complete value”, and it cannot compute wrong.
One run looks like this.
dotnet run --project samples-en\chapter22\client -- --base http://127.0.0.1:7860
== 1 Login
200 alice
== 2 API list
110 names by default, 113 with ?all_endpoints=true
/API Clean up public in the default list
/API Stream public in the default list
/API Undocumented undocumented only in all_endpoints
/API Intermediate Step - in neither list
== 3 Direct call
POST /gradio_api/run/API Clean up -> 200
Body 12 lines, first line "Wrapping loo"
Statistics 12 lines, 109 characters, longest line 12 characters
== 4 Job-style call
POST /gradio_api/call/API Clean up -> 200 {"event_id":"0367afaa297045b58a4506f35a1e2b5f"}
event: complete
data: ["Wrapping loo\n...", "12 lines, 109 characters, longest line 12 characters"]
The results of section 3 and section 4 are identical, and that is no coincidence. Both routes go through the same handler function, the same parameter list, and the same post-processing. The result an API returns must match the result of one click on the UI; that is the premise of a trustworthy API. If they differ, the problem is in parameter translation, not in the two routes.
The next five sections are covered separately. Section 5 is streaming, whose output 22.5 has already looked at; sections 6 through 9 are visibility, the four kinds of failure, and OpenAPI, described below in order.
The four lines in section 2 are a small summary of this chapter. In the same app, two public, one undocumented, one private — the names are all there, but whether they can be called is not the same.
Four Kinds of Errors
The client splits them into four kinds, two in section 6 and two in section 8. All four look different and are handled differently.
First kind: not logged in, 401. That is the first line of section 8. Take a client that has never logged in and ask it for the list.
Ask for the list without logging in -> 401 Not authenticated
The body also carries auth_message, the sentence from Chapter 20. All the client can do is log in again; retrying is pointless.
Second kind: the name does not exist, 404. Both lines in section 6 are this one; /call and /run give the same answer.
{"detail":"Could not infer function index for API name: API Intermediate Step"}
“Cannot recognize this name”. Not “you have no permission”. A private API and a misspelled name give the same answer, and that is deliberate. Someone probing names cannot find out which name is real. Faced with a 404, the client has only two options: change the name, or do not call it.
Third kind: the handler function says no, 500 plus a sentence in plain words. The sample’s cleanup API throws Error when the width is less than 2.
if (width is < 2)
{
throw new Error("Width must be at least 2 characters.");
}
What the client receives is this.
{"error":"Width must be at least 2 characters.","duration":10,"visible":true,"title":"Error"}
Error is “the app says no”, not “the program collapsed”, so this sentence is bound to appear in the receipt the caller reads, regardless of the ShowError switch. Chapter 17 used it for validation; here it is the API’s error contract. For a business rejection you can state in one sentence, use Error and let the caller read your exact words.
Fourth kind: the parameter type is wrong, 500 plus a sentence in English. Pass the width as a string.
{"error":"A number field's value is a number; the client sent '\"twelve\"'. (Parameter 'value')"}
This sentence is thrown by the framework during preprocessing; it is not your words, and it is in English. Reading it, the caller can only tell that it sent the wrong type; for what to send instead it has to go back to the document. That is why the parameter order has to be written into the description.
Crashes and business rejections must be kept apart. When the handler function throws an unwrapped exception, by default the client sees only {"error":null}, and the reason is only in the server’s log. This is the switch.
demo.ShowError = false; // Default: a crash only says "An error occurred", details go to the log
demo.ShowError = true; // For local single-user use: the crash reason also goes into the receipt
The sample turns on the latter. With it on, the English “wrong parameter type” sentence above appears in the receipt; turn it off and the same request returns only {"error":null}, and you have to go to the console for the reason. A real crash (throwing an unwrapped exception) is the same: with it on, it returns {"error":"Internal error","visible":true}; with it off, null.
This switch governs crashes only, not Error; the latter is always visible. For your own use on a local machine, turning it on saves trouble; the day you let others connect, turn it off, because exception messages often contain paths, SQL, and internal structure, and those things should not show up on someone else’s terminal.
One more distinction that echoes Chapter 17. Login failure and run failure are not in the same place. The former is a 400 plus one fixed sentence; the latter is a 500 plus error. The former happens before you get the page; the latter happens in the queue. When writing the client, do not expect to handle both in one branch.
22.7 API Visibility
Chapter 20 gave the definitions of the three visibility levels and said a private API returns 404. This section checks it again with the client, because “not in the document” and “cannot be called” are two different things that are often treated as one.
The actual effect of the three levels, tried one by one with the same client.
| Binding | Default list | all_endpoints | OpenAPI | Call by name |
|---|---|---|---|---|
Public | In | In | In | 200 |
Undocumented | Not in | In | Not in | 200 |
Private | Not in | Not in | Not in | 404 |
The Undocumented row is the point of this section. It only stays out of the default list; it is not uncallable. With ?all_endpoints=true it is listed all the same; call it by name and it returns an event_id all the same. So it stops no one who wants to call it. What it stops is “seeing it while flipping through the document”.
Private is the one that really blocks. It enters neither document, calling it by name returns 404, and the /run route is 404 too. In the sample, API Intermediate Step is this level. The button on the page can still be clicked as usual, but any script calling it fails.
Chapter 20 already gave the answer on how to choose among the three; here is just one line more. Undocumented is not a security measure; it stops “seeing it while flipping through the document”, not “someone wanting to call”. To block, only Private works.
One more that is easy to forget: visibility only matters when there is a name. A binding with neither a handler function nor a name is private no matter what you pass to apiVisibility. That rule is hard-coded in Blocks, not a configuration option.
One more, on the time dimension. Renaming is a breaking change. The name is the caller’s only anchor; rename a public API and every script that calls it stops working on the same day. It raises no error, only returns a 404 — the same as “name misspelled”. Count the cost of a rename in advance. Either keep a binding under the old name and add one under the new name, with both existing together for a while; or accept one break and then notify people one by one. Changing a description is free, change it whenever; changing the parameter order is not, and is just as breaking as a rename. Give param_0 a new meaning and the caller gets no warning at all; it simply goes on treating the new meaning as the old one.
Confirm once more the order when authentication and visibility stack up: door first, then curtain. An unauthenticated request to /gradio_api/info returns 401; you cannot even ask “what names are there”. Only after login does visibility get to say “is this name shown”. The reason the client’s section 2 can see 110 names is that section 1 logged in successfully. Without section 1, every later section is a 401.
22.8 Chapter Summary
This chapter turned the capabilities behind the UI into callable APIs.
- Names come from bindings: given
apiNameuses what was given; without it, derive from the handler function (method name,lambda,js_fn,unnamed); collisions add a numeric suffix, both given and derived. Do not put slashes in a name, and percent-encode names with spaces or non-ASCII letters. - Write the description in
apiDescription. It goes into/info’sdescriptionand OpenAPI’ssummary;endpointDescriptionis only its substitute, and when both are written the former wins. Parameter names are positional names likeparam_0, so the order must be written into the description. - The two documents divide the work.
/infoanswers “what names are there, how many parameters”; OpenAPI answers “how to send a request”. The former is for people, the latter for machines; OpenAPI has no/runand no security scheme, so do not use it to judge whether login is required. - Two call routes:
/runasks once all the way through, skips the queue, and gives only the first frame for streaming;/callsubmits a job and takes a number, goes through the queue, and gives streaming frame by frame. If you need the process, you can only take the latter. - Streaming frames are named events: the
event:line gives the type anddata:holds only outputs; the types aregenerating/complete/error/heartbeat. The first frame is complete, intermediate frames areappend/replacepatches, and the lastcompleteframe is complete again. To only get the result, wait forcomplete; to get the process, stack the patches yourself. - Errors come in four kinds: 401 means log in again, 404 means change the name, 500 plus
erroris a business rejection (Erroris always visible), and a wrong parameter type is the framework’s English. A crash by default only says “An error occurred”; only withShowErroron does it give the reason. - Visibility is a curtain, not a wall.
Privatereally blocks (404);Undocumentedonly stays out of the default list (?all_endpoints=truesees it, calling by name works). The UI is not governed by it.
The costs need stating too. There is one more contract to maintain (rename it and callers break, write the description vaguely and callers have to guess; one more boundary to guard), default-public means you have to actively remember which ones should be private; and there is one more difference you cannot see in the documents. /run and /call behave differently with the queue, and OpenAPI will not tell you that difference.
What you get in exchange is that the workbench’s capabilities no longer belong only to that page. A script, a scheduled task, another program — all can use the same logic and the same results, and the results they see are the same as the ones you see when you click a button.
Before you open the APIs to others, go through this sequence.
- Open
/gradio_api/info, count the names, and confirm nothing that should be hidden is left exposed; - For every name you want public, confirm it has an
apiDescriptionand that the description spells out the parameter order; - Call once with
/runand compare the result with one click on the page; - Call a streaming API once with
/calland confirm you can read both intermediate frames and the completion frame; - Call a private name once and confirm it is 404, not 200;
- Call
/gradio_api/infoonce without logging in and confirm it is 401; - Send a parameter of the wrong type and confirm the caller reads enough to fix it itself.