Calling Veo 3.1 from C# and .NET 8: Submit, Poll, Download, Retry and Cancel, with Measured Results for Lite, Fast and Quality
The same prompt rendered by veo3.1-lite, veo3.1-fast and veo3.1-quality from our test app.
Integrating an AI video API into a .NET application takes more than just sending a text prompt. The server takes a request, analyzes it in the background, and then provides a downloaded file later; this is how most video creation works asynchronously. So, a reliable C# client must manage task IDs, polling, storage, cancellation, and network failures.
This article demonstrates a lightweight technique using System.Text.Json, HttpClient, and .NET 8. Here we see a made-up outdoor gear business that makes quick movies showcasing its products. Verify that the endpoint URLs and model identifiers match the provider’s current documentation and the API response structure provided Veo 3.1 APIÂ test project..
1. Understand the API Workflow
The process has four steps. First, enter a prompt and the generation settings. Save the returned task ID next. Then, check the task status frequently until processing is complete. Finally, save the movie to your computer before the link becomes live.
The example gateway may receive requests for the status of tasks through the POST /v1/videos/generations and GET /v1/tasks/{id}. A request may specify an aspect ratio such as 16:9 or 9:16,. Which combinations are accessible are determined by regulations that are particular to each provider.
In production software, it is a common mistake to assume that request acceptance means the video is complete. Keep the submission and completion processes distinct.
2. Create a .NET 8 Console Application
Start a project from the terminal:
dotnet new console -n VeoDemo cd VeoDemo
No additional packages are needed for the core example. Keep credentials outside source control using environment variables:
- VIDEO_API_BASE: The provider’s base URL, ending in /v1/.
- VIDEO_API_KEY: The API authentication key.
- VIDEO_MODEL: The model identifier supported by that provider.
Providers such as APIMart offer access to video-generation models through an API gateway. Check the provider’s current request schema, model names and billing rules before running code.
3. Submit a Request and Poll for Completion
The following example illustrates submission, status checks and file download. It assumes the response structure used in the source project, where submission returns data[0].task_id, and completed tasks contain data.result.videos[0].url[0].
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("VIDEO_API_BASE")!;
var apiKey = Environment.GetEnvironmentVariable("VIDEO_API_KEY")!;
var model = Environment.GetEnvironmentVariable("VIDEO_MODEL")!;
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
var request = new {
model,
prompt = "Hiking boots crossing a stream at sunrise",
duration = 8,
aspect_ratio = "16:9",
resolution = "720p"
};
using var submit = await http.PostAsJsonAsync("videos/generations", request);
submit.EnsureSuccessStatusCode();
using var submitted = JsonDocument.Parse(await submit.Content.ReadAsStringAsync());
string id = submitted.RootElement.GetProperty("data")[0]
.GetProperty("task_id").GetString()!;
for (int attempt = 0; attempt < 90; attempt++) {
await Task.Delay(TimeSpan.FromSeconds(5));
using var response = await http.GetAsync($"tasks/{id}");
response.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var task = json.RootElement.GetProperty("data");
string status = task.GetProperty("status").GetString()!;
if (status is "failed" or "cancelled")
throw new InvalidOperationException($"Video task: {status}");
if (status != "completed") continue;
string url = task.GetProperty("result").GetProperty("videos")[0]
.GetProperty("url")[0].GetString()!;
await using var video = await http.GetStreamAsync(url);
await using var file = File.Create("video.mp4");
await video.CopyToAsync(file);
Console.WriteLine($"Saved video.mp4; task ID: {id}");
return;
}
throw new TimeoutException($"Task {id} is still running; check it later.");
This is a teaching example, not a complete production client. It demonstrates the sequence clearly while leaving room for retries, persistent task storage and application logging.
4. Avoid Duplicate Charges During Retries
In most cases, retrying after experiencing a brief network outage while checking status is quite safe. This is different from a rejected submission. The server may produce and bill for a duplicate job if it automatically submits again when the network disconnects after accepting a POST.
For temporary GET problems, such as HTTP 429 or 503, set up retries with exponential backoff. Retry generating requests carefully. Retry with provider-supported idempotency keys or reconcile submissions with uncertainty if possible.
Instantly record each task ID that is returned in a database or long-term journal. Resuming polling the current task rather than creating a new clip is possible if the program restarts.
5. Handle Cancellation and Concurrency
Even if the application’s waiting operation can be canceled using a CancellationToken, it won’t necessarily cancel work already running on the provider’s server. However, the remote operation finished later and was billed even though waiting ceased in the original test project after 15 seconds.
Apps should notify users of this difference and retain task IDs until the outcome is known. To restrict the number of simultaneous requests for batches, use SemaphoreSlim. Compared with the minimum cumulative render time of 426 seconds when processed sequentially, the provided tests produced five clips with three concurrent slots in 209 seconds.
6. Validate Requests and Handle Errors
Before you submit, make sure the question, model ID, time, resolution, and aspect ratio are all valid. HTTP 401 indicates an authentication issue, while HTTP 400 often indicates an invalid request. Fix these issues instead of retrying. Submitting an assignment does not ensure success. Never declare a queued video as finished; instead, verify its final status and record the reason.
7. Monitor Performance, Costs and Downloads
The source project’s three-tier comparison produced the following results for one shared prompt:
| Tier | Render time | Reported cost |
| Lite | 61 seconds | $0.063 |
| Fast | 136 seconds | $0.126 |
| Quality | 91 seconds | $0.90 |
These numbers reflect only that trial run; they do not reflect promised results or the going rate for the service. Applications shouldn’t assume queue time based on a tier name; the Fast tier took longer than Quality.
Consider the polling frequency as well. There were 43 status requests across all five activities when checking every five seconds. This dropped to 26 requests after exponential backoff, with an average completion time of about six seconds.
Download the findings quickly before the URLs for the created files expire. Note the task ID, model, prompt, completion progress, and actual fee. To add up monetary quantities, use decimal notation instead of double.
Conclusion
You require dependable submission, persistent task tracking, regulated polling, safe retries, cancellation handling, and quick file storage for a practical .NET 8 integration with Veo 3.1. Without any extra dependencies, HttpClient and System.Text.Json provide the necessary building blocks. Get a tiny, working client up and running first, check the chosen API’s existing schema, then add production workload precautions one step at a time.
