Why does your website need a brain? ChatGPT API + JavaScript
\n\nImagine: a user visits your site, and instead of a static page, there's a live assistant. It writes code, translates text, generates ideas, or simply holds a conversation. Sounds like science fiction? In reality, it's just a couple of dozen lines of JavaScript and one API request to ChatGPT.
\n\nIn this article, we'll break down how to connect the ChatGPT API in JavaScript — from registering a key to a full-fledged chatbot. You'll learn how to send requests, handle errors, and get the most out of the neural network. Let's go!
\n\nWhat is the ChatGPT API and why do you need it
\n\nThe OpenAI API is a bridge between your code and a giant language model (GPT-4, GPT-3.5). You send text (a prompt), and the model returns a generated response. It's simple, but the possibilities are endless.
\n\nIntegration with JavaScript is especially convenient: you can use fetch in the browser or axios / node-fetch on the server (Node.js). No complex libraries — just HTTP and JSON.
\n\nWhere this is useful on an educational site like PythonLib:
\n- \n
- Interactive assistant — answers questions about Python. \n
- Code generator — writes examples based on user requests. \n
- Homework checker — analyzes student code. \n
- Tech support chatbot — responds 24/7. \n
Step 1. Get your OpenAI API key
\n\nYou can't go anywhere without a key. Go to platform.openai.com, register, and navigate to the API Keys section. Click Create new secret key — copy it immediately. Keep the key secret, don't embed it in client-side code!
\n\nFor testing, the free balance (usually $5-18) is enough. But remember: requests to the model cost money, albeit pennies.
\n\nStep 2. Simplest request in JavaScript (Node.js)
\n\nThe fastest way to try it is to write a script in Node.js. Install node-fetch (or use the built-in fetch in Node 18+).
// chatgpt.js\nimport fetch from 'node-fetch';\n\nconst API_KEY = 'your_secret_key';\nconst API_URL = 'https://api.openai.com/v1/chat/completions';\n\nasync function askChatGPT(prompt) {\n const response = await fetch(API_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${API_KEY}`\n },\n body: JSON.stringify({\n model: 'gpt-3.5-turbo', // or gpt-4\n messages: [\n { role: 'user', content: prompt }\n ],\n temperature: 0.7,\n max_tokens: 500\n })\n });\n\n const data = await response.json();\n return data.choices[0].message.content;\n}\n\n// Usage\nconst answer = await askChatGPT('Write a Python function for sorting a list');\nconsole.log(answer);\n\nRun node chatgpt.js — and the neural network will answer you with code. Magic!
Breaking down the request structure
\nIn the request body, we pass:
\n- \n
- model — which version of GPT (gpt-3.5-turbo is faster and cheaper, gpt-4 is smarter). \n
- messages — an array of messages. You can add system (model instructions), assistant (context), and user. \n
- temperature — response creativity (0 — strict facts, 1 — creativity). \n
- max_tokens — maximum response length in tokens (1 token ≈ 0.75 words). \n
Step 3. Integrating the ChatGPT API in JavaScript in the browser
\n\nThere's a nuance here: never send the API key from client-side code — it will be stolen. Use a server proxy (Node.js, Python) or Edge Functions.
\n\nBut for a demo