OpenAI GPT in ASP.NET Core Web API step-by-step tutorial with API and code illustration

How to Integrate OpenAI GPT in ASP.NET Core Web API – Step-by-Step Tutorial

What is OpenAI GPT?

Why Integrate GPT with ASP.NET Core?

Prerequisites

Step 1: Create a New ASP.NET Core Web API Project

dotnet new webapi -n OpenAIGPTDemo
cd OpenAIGPTDemo

Step 2: Install the OpenAI NuGet Package

dotnet add package OpenAI

Step 3: Get Your OpenAI API Key

sk-proj-abc123xyz456....

Step 4: Configure Your OpenAI API Key

{
  "OpenAI": {
    "ApiKey": "YOUR_OPENAI_API_KEY"
  }
}
builder.Services.AddSingleton(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    var apiKey = config["OpenAI:ApiKey"];

    return new OpenAIClient(new OpenAIAuthentication(apiKey));
});

Important Security Note

Step 5: Create the GPT Request Model and GPT Controller for OpenAI GPT in ASP.NET Core Web API

namespace OpenAIGPTDemo.Models
{
    public class GPTRequest
    {
        public string Prompt { get; set; }
    }
}
using Microsoft.AspNetCore.Mvc;
using OpenAI;
using OpenAI.Chat;
using OpenAIGPTDemo.Models;

[ApiController]
[Route("api/[controller]")]
public class GPTController : ControllerBase
{
    private readonly OpenAIClient _client;

    public GPTController(OpenAIClient client)
    {
        _client = client;
    }

    [HttpPost("generate-text")]
    public async Task<IActionResult> GenerateText([FromBody] GPTRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Prompt))
            return BadRequest("Prompt cannot be empty.");

        try
        {
            var chatResponse = await _client.ChatCompletions.CreateCompletionAsync(
                model: "gpt-4o-mini", // Choose your model here
                messages: new[]
                {
                    new ChatMessage(ChatRole.User, request.Prompt)
                }
            );

            var result = chatResponse.Choices[0].Message.Content;

            return Ok(new { response = result });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { error = ex.Message });
        }
    }
}

Explanation:

Step 6: Test Your OpenAI GPT in ASP.NET Core Web API Using Swagger

dotnet run
Swagger UI displaying a POST API endpoint /api/GPT/generate-text with a JSON input box containing a prompt about explaining ASP.NET Core Web API with AI integration.

Example Request Body

{
  "prompt": "Explain ASP.NET Core Web API in simple terms with AI integration."
}

Example JSON Response

{
  "response": "ASP.NET Core Web API is a framework in .NET that helps developers build backend services for applications. With AI integration, these APIs can do more than just send and receive data—they can process information, make predictions, or provide smart features like chatbots, recommendations, or data analysis for websites and mobile apps."
}

Best Practices for GPT Integration

Advanced Features

Frequently Asked Questions (FAQs)

Conclusion

🚀 Subscribe for Tech Updates

📧

👤

We respect your privacy. Unsubscribe anytime.

Leave a Comment

Your email address will not be published. Required fields are marked *