Generative AI  

πŸš€ Using Generative AI APIs in C# Development

πŸ” Introduction

Generative AI APIs, such as OpenAI GPT, Azure OpenAI, Hugging Face, and Google Gemini, have transformed software development. These APIs allow developers to generate text, code, documentation, test cases, and even database queries dynamically β€” all from within their C# applications.

In this article, we’ll explore how to use Generative AI APIs in C#, including setup, coding examples, and real-world use cases.

🧠 What Is a Generative API?

A Generative API is a cloud-based service that takes input text (a prompt) and produces meaningful output such as code, summaries, or responses.

Common providers:

  • OpenAI API (ChatGPT, GPT-4, GPT-4o, etc.)

  • Azure OpenAI Service

  • Google Gemini API

  • Hugging Face Inference API

βš™οΈ Prerequisites

Before starting, ensure you have:

  • Visual Studio 2022 or VS Code

  • .NET 6 or higher

  • An API key from OpenAI, Azure OpenAI, or any other provider

πŸ’» Example 1: Using OpenAI GPT API in C#

This example demonstrates how to connect your C# app to the OpenAI GPT API to generate responses programmatically.

Step 1. Install NuGet Package

Open the Package Manager Console and install:

Install-Package OpenAI_API

Step 2. Write the C# Code

using System;
using System.Threading.Tasks;
using OpenAI_API;

namespace GenerativeAIExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Your API key
            string apiKey = "sk-your-openai-key";

            // Initialize API
            var api = new OpenAIAPI(apiKey);

            // Prompt
            Console.Write("Enter your prompt: ");
            string prompt = Console.ReadLine();

            // Generate completion
            var result = await api.Completions.GetCompletion(prompt);

            Console.WriteLine("\nAI Response:");
            Console.WriteLine(result);
        }
    }
}

Output Example

Enter your prompt: Write a function to reverse a string in C#
AI Response:
public string ReverseString(string input)
{
    char[] arr = input.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

🧩 Example 2: Using Generative API for Code Generation

You can use the API to generate C#, SQL, or JavaScript code snippets dynamically β€” helpful for developers automating code creation or documentation.

string prompt = "Generate a SQL query to fetch all employees with salary > 50000";

var result = await api.Completions.GetCompletion(prompt);
Console.WriteLine("Generated Query: " + result);

βœ… Output

SELECT * FROM Employees WHERE Salary > 50000;

πŸ§ͺ Example 3: Generative API for Unit Test Creation

AI can even create test cases automatically for existing functions.

string prompt = "Write NUnit test cases for a C# function that adds two numbers.";
var result = await api.Completions.GetCompletion(prompt);

Console.WriteLine(result);

βœ… Output

[TestFixture]
public class CalculatorTests
{
    [Test]
    public void Add_TwoNumbers_ReturnsSum()
    {
        var result = Calculator.Add(2, 3);
        Assert.AreEqual(5, result);
    }
}

πŸ” Example 4: Using Azure OpenAI API in C#

If you’re using Azure OpenAI, use HttpClient for REST calls:

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class AzureOpenAIExample
{
    private static readonly string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/";
    private static readonly string apiKey = "YOUR_AZURE_API_KEY";

    public static async Task Main()
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("api-key", apiKey);

        var body = new
        {
            prompt = "Write C# code to sort an array using bubble sort.",
            max_tokens = 150
        };

        var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");

        HttpResponseMessage response = await client.PostAsync($"{endpoint}openai/deployments/text-davinci-003/completions?api-version=2023-05-15", content);

        string result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

🌍 Real-World Use Cases

Use CaseDescription
Code AssistantGenerate functions, SQL queries, and documentation
Testing AutomationGenerate unit test cases dynamically
Chatbot DevelopmentBuild smart chat interfaces with AI
Content GenerationWrite blogs, summaries, and ad copies
Error ExplanationInput exception messages, get human-readable explanations

πŸ“ˆ Benefits for Developers

βœ… Speeds up development time
βœ… Reduces manual repetitive coding
βœ… Boosts code quality & documentation
βœ… Helps in prototyping and brainstorming ideas

πŸ”— External References

🧾 Conclusion

Generative APIs are reshaping software development by enabling AI-assisted coding, automation, and innovation.

By integrating these APIs into your C# applications, you can build intelligent systems that generate, understand, and enhance code β€” bringing the power of AI directly into your development workflow.