๐Ÿ“ฅList, Fetch, and Download Documents

This snippet mirrors the document retrieval recipe using C#.

// Requires .NET 7+.
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;

var token = Environment.GetEnvironmentVariable("AUTOCONTENT_TOKEN") ?? "YOUR_API_TOKEN";
var documentId = Environment.GetEnvironmentVariable("DOCUMENT_ID") ?? "YOUR_REQUEST_ID";
var baseUrl = "https://api.autocontentapi.com";

static string ExtensionFromContentType(string? contentType)
{
    if (contentType is null) return ".txt";
    if (contentType.Contains("pdf", StringComparison.OrdinalIgnoreCase)) return ".pdf";
    if (contentType.Contains("html", StringComparison.OrdinalIgnoreCase)) return ".html";
    return ".txt";
}

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var listBody = await client.GetStringAsync($"{baseUrl}/documents/get?page=1&pageSize=10");
Console.WriteLine("Documents page:");
Console.WriteLine(listBody);

var singleBody = await client.GetStringAsync($"{baseUrl}/documents/{documentId}");
Console.WriteLine("Single document:");
Console.WriteLine(singleBody);

var downloadResponse = await client.GetAsync($"{baseUrl}/documents/{documentId}/download");
if (!downloadResponse.IsSuccessStatusCode)
{
    Console.Error.WriteLine("Download failed: " + (int)downloadResponse.StatusCode + " " + downloadResponse.ReasonPhrase);
    Console.Error.WriteLine(await downloadResponse.Content.ReadAsStringAsync());
    Environment.Exit(1);
}

var extension = ExtensionFromContentType(downloadResponse.Content.Headers.ContentType?.MediaType);
var bytes = await downloadResponse.Content.ReadAsByteArrayAsync();
var outputPath = $"briefing-document-{documentId}{extension}";
await File.WriteAllBytesAsync(outputPath, bytes);
Console.WriteLine($"Saved {outputPath}");

Replace YOUR_API_TOKEN (or set AUTOCONTENT_TOKEN) and DOCUMENT_ID before running.

See also

Last updated