How to Build a Simple API with ChatGPT in Less than 2 Hours
How to Build a Simple API with ChatGPT in Less than 2 Hours
In 2026, the buzz around AI tools like ChatGPT is undeniable, but many builders still struggle with integrating these technologies into their projects. If you're an indie hacker or a solo founder looking to leverage ChatGPT for your next side project, building a simple API might seem daunting. However, with the right guidance, you can set it up in less than two hours, even if you're not a coding expert.
Prerequisites: What You Need Before You Start
Before diving in, make sure you have the following:
- Basic programming knowledge: Familiarity with JavaScript or Python will be helpful.
- OpenAI API Key: Sign up on OpenAI to get your API key (free tier available).
- Node.js or Python installed: You can download Node.js here or Python here.
Step 1: Setting Up Your Development Environment
-
Create a new project directory: Open your terminal and run:
mkdir chatgpt-api cd chatgpt-api -
Initialize your project:
- For Node.js: Run
npm init -yto create a package.json file. - For Python: Create a virtual environment with
python -m venv venvand activate it.
- For Node.js: Run
-
Install necessary packages:
- For Node.js:
npm install express axios dotenv - For Python:
pip install Flask requests python-dotenv
- For Node.js:
Step 2: Writing the API Code
Node.js Example
Create a file named server.js and add the following code:
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
app.post('/api/chatgpt', async (req, res) => {
const userInput = req.body.input;
try {
const response = await axios.post('https://api.openai.com/v1/chat/completions', {
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: userInput }],
}, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
});
res.json(response.data.choices[0].message.content);
} catch (error) {
res.status(500).send('Error communicating with ChatGPT');
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Python Example
Create a file named app.py and add the following code:
from flask import Flask, request, jsonify
import requests
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
@app.route('/api/chatgpt', methods=['POST'])
def chatgpt():
user_input = request.json['input']
headers = {
'Authorization': f'Bearer {os.getenv("OPENAI_API_KEY")}',
'Content-Type': 'application/json',
}
data = {
'model': 'gpt-3.5-turbo',
'messages': [{'role': 'user', 'content': user_input}],
}
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=data)
return jsonify(response.json()['choices'][0]['message']['content'])
if __name__ == '__main__':
app.run(port=3000)
Step 3: Testing Your API
-
Run your server:
- For Node.js: Execute
node server.js. - For Python: Execute
python app.py.
- For Node.js: Execute
-
Test with Postman or Curl: Send a POST request to
http://localhost:3000/api/chatgptwith a JSON body:{ "input": "What is the future of AI?" }
Troubleshooting: What Could Go Wrong
- API Key Issues: Ensure your API key is correctly set in your environment variables.
- CORS Issues: If you plan to use this API in a front-end application, set up CORS in your server code.
- Network Errors: Double-check your internet connection and the OpenAI API status.
What's Next: Building on Your API
Once you have your API up and running, consider adding features like:
- User authentication: Secure your API to prevent misuse.
- Rate limiting: Control the number of requests to your API.
- Frontend integration: Build a simple interface using React or Vue.js to interact with your API.
Conclusion: Start Here
Building a simple API with ChatGPT doesn't have to be complicated or time-consuming. With the steps outlined above, you can have a functional API in less than two hours. Remember to leverage your project further by adding features that enhance user experience.
If you're looking for tools and frameworks to support your journey, we recommend checking out our other resources at Built This Week, where we discuss the latest tools and share our building experiences.
Follow Our Building Journey
Weekly podcast episodes on tools we're testing, products we're shipping, and lessons from building in public.