Claude API C# Integration Guide for .NET Developers
Claude API C# Integration Guide
If you're building a .NET application and want to add Claude's language capabilities, you don't need an official SDK to get started — the Claude API is a standard HTTPS JSON API, and C# developers can call it with nothing more than HttpClient and System.Text.Json. This guide walks through setting up authentication, sending a message request, parsing the response, and handling streaming output in C#.
The short answer: create an HttpClient, set the required headers (API key, version header, content type), POST a JSON body to the messages endpoint, and deserialize the response into your own model classes. Everything below shows exactly how that looks in idiomatic C#, including error handling and streaming with IAsyncEnumerable.
Prerequisites
- .NET 6 or later (examples use top-level statements and
System.Text.Json) - An API key for whichever Claude access you're using
Newtonsoft.Jsonis optional —System.Text.Jsonis sufficient and ships with .NET
Basic request with HttpClient
Here's a minimal working example that sends a single user message and reads back the text response:
using System.Net.Http.Json;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("CLAUDE_API_KEY");
var client = new HttpClient { BaseAddress = new Uri("https://api.anthropic.com/") };
client.DefaultRequestHeaders.Add("x-api-key", apiKey);
client.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
var requestBody = new
{
model = "claude-3-5-sonnet-20241022",
max_tokens = 1024,
messages = new[]
{
new { role = "user", content = "Explain dependency injection in C# in two sentences." }
}
};
var response = await client.PostAsJsonAsync("v1/messages", requestBody);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
var text = doc.RootElement.GetProperty("content")[0].GetProperty("text").GetString();
Console.WriteLine(text);
This pattern — headers on the client, strongly typed anonymous objects for the request body, JsonDocument or a typed model for the response — covers most C# integrations without pulling in a third-party package.
Using strongly typed models instead of JsonDocument
For anything beyond a quick script, define response models so you get compile-time safety and IntelliSense:
public record ContentBlock(string Type, string? Text);
public record MessageResponse(string Id, string Role, List<ContentBlock> Content, Usage Usage);
public record Usage(int InputTokens, int OutputTokens);
var result = await response.Content.ReadFromJsonAsync<MessageResponse>(
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }
);
Console.WriteLine(result?.Content[0].Text);
Note the PropertyNamingPolicy — Claude's JSON uses snake_case fields (input_tokens, stop_reason), and System.Text.Json's snake_case policy (available in newer .NET versions) handles the mapping automatically.
Handling errors
Claude-compatible APIs return structured error bodies with an HTTP status code and a JSON error object. Wrap your call so you can distinguish between rate limits, auth failures, and malformed requests:
if (!response.IsSuccessStatusCode)
{
var errorBody = await response.Content.ReadAsStringAsync();
throw new HttpRequestException($"Request failed ({(int)response.StatusCode}): {errorBody}");
}
In production code, catch 429 separately and apply backoff, and log 401/403 as configuration issues rather than retrying blindly.
Streaming responses in C#
Streaming is where C# integrations get more interesting, since the API returns Server-Sent Events rather than a single JSON blob. You need to read the response stream line by line and parse each data: chunk:
var request = new HttpRequestMessage(HttpMethod.Post, "v1/messages")
{
Content = JsonContent.Create(new
{
model = "claude-3-5-sonnet-20241022",
max_tokens = 1024,
stream = true,
messages = new[] { new { role = "user", content = "Write a haiku about async/await." } }
})
};
using var streamResponse = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using var stream = await streamResponse.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (line is null || !line.StartsWith("data:")) continue;
var payload = line["data:".Length..].Trim();
if (payload == "[DONE]") break;
using var chunk = JsonDocument.Parse(payload);
if (chunk.RootElement.TryGetProperty("delta", out var delta) &&
delta.TryGetProperty("text", out var textToken))
{
Console.Write(textToken.GetString());
}
}
This gives you token-by-token output you can pipe into a console app, a Blazor component, or a SignalR hub for real-time UI updates.
Simplifying integration with SubToAPI
If you'd rather not manage raw API keys, rate limits, or streaming parsing yourself across multiple services, SubToAPI turns your existing Claude access into a straightforward HTTPS API with application keys (sub_live_...), built-in usage metadata, and team seats. The request shape in C# stays almost identical — you just point BaseAddress at https://api.subtoapi.app/v1/ and use your SUBTOAPI_KEY:
client.BaseAddress = new Uri("https://api.subtoapi.app/v1/");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SUBTOAPI_KEY")}");
Everything else — the messages payload, streaming loop, error handling — works the same way, which makes it a drop-in option if you want per-application keys and billing visibility without rewriting your C# client code. See the quickstart and messages docs for the full endpoint reference, and streaming for SSE details specific to SubToAPI. Pricing starts with a free trial at signup, with plans listed on the pricing page.
Tool use from C#
If your application needs Claude to call functions — looking up data, running calculations, triggering actions — define a tools array in the same request body with JSON Schema parameters, then inspect the response for tool_use content blocks:
var tools = new[]
{
new
{
name = "get_order_status",
description = "Look up the status of a customer order by ID",
input_schema = new
{
type = "object",
properties = new { order_id = new { type = "string" } },
required = new[] { "order_id" }
}
}
};
When Claude responds with a tool_use block, your C# code executes the corresponding method and sends the result back as a tool_result message in the next turn. SubToAPI's tools documentation covers the full request/response cycle if you're wiring this into a .NET backend.
Putting it together in an ASP.NET Core service
In a real application, wrap this logic in a typed HttpClient registered via IHttpClientFactory, inject it into your controllers or services, and keep your API key in configuration (appsettings.json + environment variable overrides, or Azure Key Vault) rather than hardcoded strings. That's the only architectural change needed to move from a console script to a production ASP.NET Core integration.
questions
Do I need an official Anthropic SDK for C#? No. There's no first-party C# SDK, but the API is plain JSON over HTTPS, so HttpClient and System.Text.Json are enough for a full integration, including streaming.
How do I handle streaming responses in .NET? Read the HTTP response as a stream, parse it line by line for data: prefixed Server-Sent Events, and extract the delta.text field from each JSON chunk until you see [DONE].
Can I use SubToAPI instead of calling Claude directly in C#? Yes — the request and response format are nearly identical, so you can point your existing HttpClient code at https://api.subtoapi.app/v1/ with a sub_live_... key and keep the same C# logic.