Ai Coding Tools

How to Build a Simple API with ChatGPT in Less than 2 Hours

By BTW Team3 min read

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

  1. Create a new project directory: Open your terminal and run:

    mkdir chatgpt-api
    cd chatgpt-api
    
  2. Initialize your project:

    • For Node.js: Run npm init -y to create a package.json file.
    • For Python: Create a virtual environment with python -m venv venv and activate it.
  3. Install necessary packages:

    • For Node.js:
      npm install express axios dotenv
      
    • For Python:
      pip install Flask requests python-dotenv
      

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

  1. Run your server:

    • For Node.js: Execute node server.js.
    • For Python: Execute python app.py.
  2. Test with Postman or Curl: Send a POST request to http://localhost:3000/api/chatgpt with 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.

Subscribe

Never miss an episode

Subscribe to Built This Week for weekly insights on AI tools, product building, and startup lessons from Ryz Labs.

Subscribe
Ai Coding Tools

How to Optimize Your Workflow with AI Coding Tools: 5 Productivity Hacks

How to Optimize Your Workflow with AI Coding Tools: 5 Productivity Hacks In 2026, AI coding tools have become essential for indie hackers, solo founders, and side project builders

Jul 4, 20263 min read
Ai Coding Tools

How to Improve Your Coding Efficiency with AI in Just 15 Minutes a Day

How to Improve Your Coding Efficiency with AI in Just 15 Minutes a Day As a solo founder or indie hacker, time is always at a premium, especially when it comes to coding. The thoug

Jul 4, 20264 min read
Ai Coding Tools

Cursor vs Codeium: Which AI Coding Tool Actually Saves You Time?

Cursor vs Codeium: Which AI Coding Tool Actually Saves You Time? As a solo founder or indie hacker, your time is incredibly valuable. You need tools that genuinely enhance your pro

Jul 4, 20263 min read
Ai Coding Tools

Top 5 AI Coding Tools for Beginners to Master in 2026

Top 5 AI Coding Tools for Beginners to Master in 2026 As we dive into 2026, the landscape of coding has been transformed by AI tools that help beginners get up to speed without the

Jul 4, 20264 min read
Ai Coding Tools

Why GitHub Copilot is Overrated: A Deep Dive on Its Limitations

Why GitHub Copilot is Overrated: A Deep Dive on Its Limitations As a solo founder or indie hacker, you're probably looking for every edge you can get to build your product faster a

Jul 4, 20264 min read
Ai Coding Tools

How to Master AI Coding Tools in Just 30 Minutes Every Day

How to Master AI Coding Tools in Just 30 Minutes Every Day In 2026, the landscape of coding is rapidly evolving, and AI coding tools are at the forefront of this transformation. Bu

Jul 4, 20265 min read