Introduction
Large language models (LLMs) are now a normal part of application development. Anthropic's Claude is one of the most widely used models, and you can call it from any language that can send an HTTP request, including C#.
In this article, we'll build a small .NET console app that sends a question to Claude and prints the answer. No extra libraries are needed: we'll use HttpClient and System.Text.Json, which come with .NET.
Prerequisites
- .NET 8 SDK (or later) installed
- Visual Studio, VS Code or Rider
- An Anthropic API key from the Anthropic Console (console.anthropic.com)
Step 1: Create a console project
Open a terminal and run:
dotnet new console -n ClaudeDemo
cd ClaudeDemoStep 2: Store your API key safely
Never hard-code an API key in your source code. Store it in an environment variable instead.
Windows (PowerShell):
setx ANTHROPIC_API_KEY "your-api-key-here"macOS / Linux:
export ANTHROPIC_API_KEY="your-api-key-here"Restart your terminal or IDE after setting it.
Step 3: Understand the request
Claude's Messages API is a single HTTP endpoint:
- URL:
https://api.anthropic.com/v1/messages - Method: POST
- Headers:
x-api-key: your API keyanthropic-version:2023-06-01content-type:application/json
- Body: the model name, a maximum token limit, and a list of messages
Step 4: Write the code
Replace the contents of Program.cs with:
using System.Net.Http;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
?? throw new InvalidOperationException("Set the ANTHROPIC_API_KEY environment variable.");
using var http = new HttpClient();
http.DefaultRequestHeaders.Add("x-api-key", apiKey);
http.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
var requestBody = new
{
model = "claude-sonnet-5-5",
max_tokens = 500,
system = "You are a helpful assistant for software testers. Keep answers short and practical.",
messages = new[]
{
new { role = "user", content = "Write 3 test cases for a login page." }
}
};
var json = JsonSerializer.Serialize(requestBody);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await http.PostAsync("https://api.anthropic.com/v1/messages", content);
var responseText = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Error {(int)response.StatusCode}: {responseText}");
return;
}
using var doc = JsonDocument.Parse(responseText);
var answer = doc.RootElement
.GetProperty("content")[0]
.GetProperty("text")
.GetString();
Console.WriteLine(answer);
Join the conversation! Your thoughts help the community grow.