Header Ads

Integrate ChatGPT API with Angular: Complete Tutorial 2025

 How to Integrate ChatGPT API with Angular: A Complete Step-by-Step Guide

Integrating ChatGPT into your Angular application opens up a world of possibilities — from AI-powered chatbots and smart search to intelligent assistants and content generators. In this step-by-step tutorial, you will learn exactly how to connect the OpenAI ChatGPT API with an Angular application and build a working chat interface.


Prerequisites

Before starting, make sure you have the following ready:

  • Angular 15 or higher installed
  • An OpenAI API key from platform.openai.com
  • Basic knowledge of Angular components and services


Step 1: Create a New Angular Project

ng new angular-chatgpt

cd angular-chatgpt

ng serve


Step 2: Store Your API Key Securely

Never hardcode your API key directly in a component. Always store it in the environment.ts file and add that file to .gitignore to keep your key private.

// src/environments/environment.ts

export const environment = {

  production: false,

  openaiApiKey: 'YOUR_OPENAI_API_KEY_HERE'

};


Step 3: Create a ChatGPT Service

Create a dedicated Angular service to handle all communication with the OpenAI API. This keeps your component clean and your API logic reusable.

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';

import { environment } from '../../environments/environment';


@Injectable({ providedIn: 'root' })

export class ChatgptService {

  private apiUrl = 'https://api.openai.com/v1/chat/completions';


  constructor(private http: HttpClient) {}


  sendMessage(userMessage: string): Observable<any> {

    const headers = new HttpHeaders({

      'Content-Type': 'application/json',

      'Authorization': `Bearer ${environment.openaiApiKey}`

    });

    const body = {

      model: 'gpt-3.5-turbo',

      messages: [

        { role: 'system', content: 'You are a helpful assistant.' },

        { role: 'user', content: userMessage }

      ],

      max_tokens: 500

    };

    return this.http.post(this.apiUrl, body, { headers });

  }

}


Step 4: Create the Chat Component

export class ChatComponent {

  messages: any[] = [];

  userInput = '';

  isLoading = false;


  constructor(private chatgptService: ChatgptService) {}


  sendMessage() {

    if (!this.userInput.trim()) return;

    this.messages.push({ role: 'user', content: this.userInput });

    const question = this.userInput;

    this.userInput = '';

    this.isLoading = true;


    this.chatgptService.sendMessage(question).subscribe({

      next: (res) => {

        this.messages.push({ role: 'assistant', content: res.choices[0].message.content });

        this.isLoading = false;

      },

      error: () => { this.isLoading = false; }

    });

  }

}


Step 5: Build the Chat Template

<div class="chat-container">

  <div class="messages">

    <div *ngFor="let msg of messages" [class]="msg.role">

      <strong>{{ msg.role === 'user' ? 'You' : 'ChatGPT' }}:</strong>

      <p>{{ msg.content }}</p>

    </div>

    <div *ngIf="isLoading"><em>ChatGPT is typing...</em></div>

  </div>

  <input [(ngModel)]="userInput" (keyup.enter)="sendMessage()" placeholder="Ask something..." />

  <button (click)="sendMessage()">Send</button>

</div>


Key Capabilities of This Integration

Once set up, this Angular ChatGPT integration supports a range of powerful features that can be extended for enterprise use:

  • Real-time AI responses to user questions
  • Conversation history tracking across messages
  • Custom system prompts for specific use cases
  • Easy integration into existing Ionic mobile apps
  • Support for streaming responses with minor changes


Conclusion

Integrating ChatGPT with Angular is straightforward using the OpenAI REST API and Angular's HttpClient. From here, you can extend this further by adding full conversation history, streaming responses, or embedding the chatbot directly into an Ionic mobile application.

For teams building SaaS products, enterprise dashboards, or workflow-driven platforms, adding AI-powered chat is a modern and practical enhancement that users will love. If you found this tutorial helpful, share it and drop a comment below!

Post a Comment

0 Comments