·AI & ChatGPT

Module 9 Lesson 1: Using ChatGPT via API

Move beyond the chat box. Learn the fundamentals of the OpenAI API, model selection, and how to build your own AI-powered apps.

Using ChatGPT via API

For Power Users, the web interface is just the tip of the iceberg. The API (Application Programming Interface) allows you to build ChatGPT directly into your own software, spreadsheets, and automated workflows.

1. The Core Components

To use the API, you need three things:

  1. API Key: Your secret password (keep it safe!).
  2. Endpoint: The URL you send requests to (e.g., https://api.openai.com/v1/chat/completions).
  3. Payload: The JSON data containing your model, messages, and settings (like Temperature).

2. Model Selection

  • gpt-4o: The fastest, cheapest, and most capable model for most tasks.
  • gpt-4-turbo: Good for complex reasoning.
  • gpt-3.5-turbo: Best for very simple, high-speed tasks.
graph LR
    User[Your App/Script] --> Request[API Request + Key]
    Request --> OpenAI[OpenAI Servers]
    OpenAI --> Process[Model Processing]
    Process --> Response[JSON Response]
    Response --> User

3. A Simple Python Example

import openai

client = openai.OpenAI(api_key="YOUR_KEY_HERE")

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain the API in 1 sentence."}
    ]
)

print(response.choices[0].message.content)

4. Rate Limits and Billing

Unlike the flat monthly fee for ChatGPT Plus, the API is Pay-As-You-Go. You are billed per 1,000 tokens.

  • Input Tokens: What you send to the AI.
  • Output Tokens: What the AI sends back.

Hands-on: Explore the API Playground

  1. Go to the OpenAI Playground.
  2. Experiment with the System Message on the left and the User Message in the middle.
  3. Use the View Code button to see how your chat would look in a Python or Node.js script.

Key Takeaways

  • The API is for building, not just chatting.
  • Security is key: Never share your API key!
  • Payloads allow for granular control over Temperature and Max Tokens.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn