How to Make C# and ChatGPT Work Together: A Complete Integration Guide
\n\nImagine: your C# application suddenly starts not just executing commands, but having meaningful conversations, writing code, translating texts, or generating ideas. Sounds like science fiction? It's already a reality thanks to ChatGPT API integration in C#. Today I'll show you how to turn an ordinary console program into an intelligent assistant in 15 minutes. Let's go!
\n\nOpenAI provides a powerful REST API that works great with .NET. You don't need any third-party SDKs — just the standard HttpClient and a couple of libraries for working with JSON. The whole process fits into four steps: get a key, send a request, parse the response, enjoy the result.
What We Need to Get Started
\n\nBefore writing code, let's prepare the environment. You will need:
\n\n- \n
- Visual Studio 2022 or JetBrains Rider (but a regular .NET SDK + notepad will also work) \n
- .NET 6.0 or higher (I use .NET 8 — it's faster) \n
- OpenAI API key — register at platform.openai.com, go to the API Keys section and create a new secret key. Note: you get $5 for testing the first time, but don't forget about limits! \n
- Newtonsoft.Json library or System.Text.Json (built into .NET, but I prefer Newtonsoft — it's more intuitive) \n
You can install Newtonsoft.Json via NuGet: Install-Package Newtonsoft.Json or through the package manager in Visual Studio.
Creating Your First Request to ChatGPT in C#
\n\nLet's start simple: send a message to the model and get a response. All the magic happens through a POST request to the endpoint https://api.openai.com/v1/chat/completions.
Here's the minimal working code that I recommend saving as a starting point:
\n\nusing System;\nusing System.Net.Http;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nclass Program\n{\n private static readonly string apiKey = "YOUR_KEY_HERE"; // Don't show this to anyone!\n private static readonly string endpoint = "https://api.openai.com/v1/chat/completions";\n\n static async Task Main(string[] args)\n {\n var client = new HttpClient();\n client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");\n\n var requestBody = new\n {\n model = "gpt-3.5-turbo",\n messages = new[]\n {\n new { role = "user", content = "Tell me a joke about programmers" }\n },\n temperature = 0.7,\n max_tokens = 150\n };\n\n var json = JsonConvert.SerializeObject(requestBody);\n var content = new StringContent(json, Encoding.UTF8, "application/json");\n\n var response = await client.PostAsync(endpoint, content);\n var responseString = await response.Content.ReadAsStringAsync();\n\n var responseObject = JObject.Parse(responseString);\n var reply = responseObject["choices"][0]["message"]["content"].ToString();\n\n Console.WriteLine("ChatGPT says:");\n Console.WriteLine(reply);\n }\n}\n\n\nYou run it — and the console outputs something like: "Why do programmers confuse Halloween and Christmas? Because Oct 31 == Dec 25!". Funny? Does it work? Great!
\n\nBreaking Down the Code
\n\nLet's look at what's happening here. We create an HttpClient, add an authorization header — this is standard practice for working with the OpenAI API in C#. The request body is a JSON object with parameters:
- \n
- model: specify the model.
gpt-3.5-turbois the sweet spot for price/quality. For complex tasks, usegpt-4, but be prepared to pay more. \n Blogs
Book Recommendations
Read also
Top Mistakes of Beginner C# Developers and How to Avoid Them
Clean Code in Kotlin: Rules That Will Save Your Nerves
TypeScript under the hood: Rate limiting and throttling without pain
Network Programming in PHP: From Sockets to Web Scraping
Getters and Setters in TypeScript: Complete Guide with Examples