Integrating C# with ChatGPT API: Step-by-Step Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Make C# and ChatGPT Work Together: A Complete Integration Guide

\n\n

Imagine: 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\n

OpenAI 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.

\n\n

What We Need to Get Started

\n\n

Before 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
\n\n

You can install Newtonsoft.Json via NuGet: Install-Package Newtonsoft.Json or through the package manager in Visual Studio.

\n\n

Creating Your First Request to ChatGPT in C#

\n\n

Let'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.

\n\n

Here's the minimal working code that I recommend saving as a starting point:

\n\n
using 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\n

You 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\n

Breaking Down the Code

\n\n

Let'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\n