Skip to Content
Code Examples.NET Example

.NET Example

This example demonstrates how to use the WebClassifAI API with .NET using the HttpClient class.

Basic Example

using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; public class WebClassifAIExample { private static readonly string API_ENDPOINT = "https://api.classifai.com/v1"; private static readonly HttpClient client = new HttpClient(); public static async Task<Dictionary<string, object>> ClassifyUrlsAsync( List<string> urls, string apiKey, string taxonomy = "iab-1.0") { var payload = new { urls = urls, api_key = apiKey, taxonomy = taxonomy }; var json = JsonSerializer.Serialize(payload); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(API_ENDPOINT, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<Dictionary<string, object>>(responseBody); } public static async Task Main() { try { string apiKey = "your_api_key_here"; var urls = new List<string> { "https://www.example.com/", "https://www.tech-blog.com/" }; var results = await ClassifyUrlsAsync(urls, apiKey); // Process results var resultsList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>( JsonSerializer.Serialize(results["results"])); foreach (var result in resultsList) { string url = result["url"].ToString(); bool scrapedSuccessfully = (bool)result["scraped_successfully"]; Console.WriteLine($"\nURL: {url}"); Console.WriteLine($"Scraped successfully: {scrapedSuccessfully}"); var predictions = JsonSerializer.Deserialize<List<Dictionary<string, object>>>( JsonSerializer.Serialize(result["predictions"])); foreach (var prediction in predictions) { Console.WriteLine("\nPrediction:"); if (prediction.ContainsKey("tier1")) { var tier1 = JsonSerializer.Deserialize<Dictionary<string, object>>( JsonSerializer.Serialize(prediction["tier1"])); Console.WriteLine($"Tier 1: {tier1["name"]} ({tier1["code"]}) - " + $"Confidence: {tier1["confidence"]:F2}"); } if (prediction.ContainsKey("tier2")) { var tier2 = JsonSerializer.Deserialize<Dictionary<string, object>>( JsonSerializer.Serialize(prediction["tier2"])); Console.WriteLine($"Tier 2: {tier2["name"]} ({tier2["code"]}) - " + $"Confidence: {tier2["confidence"]:F2}"); } } } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } }

Error Handling

For production use, implement proper error handling:

public static async Task<Dictionary<string, object>> ClassifyUrlsAsync( List<string> urls, string apiKey, string taxonomy = "iab-1.0") { try { // ... existing code ... } catch (HttpRequestException ex) { throw new Exception($"Network error: {ex.Message}", ex); } catch (TaskCanceledException ex) { throw new Exception("Request timed out", ex); } catch (JsonException ex) { throw new Exception("Invalid JSON response", ex); } }

Batch Processing

Important: For optimal performance, we strongly recommend sending multiple URLs in a single request (up to the 500 URL limit). Only split URLs into multiple requests if you have more than 500 URLs or your architecture specifically requires it.

// Process up to 500 URLs in a single request var urls = Enumerable.Repeat("https://example.com", 500).ToList(); var results = await ClassifyUrlsAsync(urls, apiKey);

Using HttpClientFactory

For better performance and resource management, use HttpClientFactory:

public class WebClassifAIClient { private readonly HttpClient _httpClient; private readonly JsonSerializerOptions _jsonOptions; public WebClassifAIClient(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("WebClassifAI"); _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; } public async Task<Dictionary<string, object>> ClassifyUrlsAsync( List<string> urls, string apiKey, string taxonomy = "iab-1.0") { var payload = new { urls = urls, api_key = apiKey, taxonomy = taxonomy }; var json = JsonSerializer.Serialize(payload); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("/v1/classify", content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<Dictionary<string, object>>( responseBody, _jsonOptions); } } // In Startup.cs or Program.cs public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("WebClassifAI", client => { client.BaseAddress = new Uri("https://api.classifai.com/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }); }

Additional Resources

Last updated on