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:

Bash
dotnet new console -n ClaudeDemo
cd ClaudeDemo

Step 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):

PowerShell
setx ANTHROPIC_API_KEY "your-api-key-here"

macOS / Linux:

Bash
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 key
    • anthropic-version: 2023-06-01
    • content-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:

C#
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);

Step 5: Run it

Bash
dotnet run

You'll see Claude's answer, three test cases for a login page, printed in your console.

How the code works

  • system sets Claude's role and behaviour. Here, we ask it to act as an assistant for software testers.
  • messages holds the conversation. Each message has a role (user or assistant) and content.
  • max_tokens limits the length of the reply, which also controls cost.
  • The response JSON contains a content array. For a normal text reply, the answer is in content[0].text.

Common errors and fixes

ErrorLikely causeFix
401 UnauthorizedMissing or wrong API keyCheck the environment variable is set and your IDE was restarted
400 Bad RequestInvalid JSON or wrong field nameCheck the model name and the messages format
429 Too Many RequestsRate limit reachedWait and retry, ideally with exponential backoff

Best practices

  1. Keep keys out of code. Use environment variables or a secrets manager.
  2. Use a system prompt to control tone and format.
  3. Set a sensible max_tokens to control cost and response length.
  4. Handle errors and retries in production code.
  5. Reuse one HttpClient (for example via IHttpClientFactory in ASP.NET Core) instead of creating a new one for every request.

What to learn next

Once this works, you can explore:

  • Multi-turn conversations: send previous messages back so Claude remembers context
  • Streaming responses: show the answer word by word as it's generated
  • Tool use: let Claude call your own C# functions
  • Model Context Protocol (MCP): connect Claude to databases, files and other systems

These topics are also part of Anthropic's Claude Certified Developer – Foundations (CCDV-F) exam, if you're planning to get certified.

Conclusion

With just HttpClient and a few lines of JSON, any .NET developer can add Claude to an application. Start with a simple console app like this, then build up to chatbots, test-case generators and AI agents.