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 Build Your First AI Project in Just 3 Hours

How to Build Your First AI Project in Just 3 Hours If you’re a solo founder or indie hacker looking to dip your toes into the world of AI, you might be wondering where to start. Th

Jul 20, 20264 min read
Ai Coding Tools

Is GitHub Copilot Really Worth the $10/Month? Let's Find Out

Is GitHub Copilot Really Worth the $10/Month? Let's Find Out As a solo founder or indie hacker, every dollar counts. When it comes to tools that promise to make your life easier—li

Jul 20, 20264 min read
Ai Coding Tools

How to Deploy Your First AI-Powered App in 2 Hours

How to Deploy Your First AIPowered App in 2 Hours Deploying an AIpowered app can feel like a daunting task. If you're a solo founder or an indie hacker, the thought of spending wee

Jul 20, 20264 min read
Ai Coding Tools

How to Write Your First Code with AI Assistance in 2 Hours

How to Write Your First Code with AI Assistance in 2026 If you're a beginner looking to get into coding, the idea of writing your first piece of code can feel daunting. What if I t

Jul 20, 20264 min read
Ai Coding Tools

10 Mistakes First-Time Coders Make with AI Tools

10 Mistakes FirstTime Coders Make with AI Tools If you're a firsttime coder stepping into the world of AI tools in 2026, you're probably excited but also a bit overwhelmed. We've b

Jul 20, 20264 min read
Ai Coding Tools

How to Build Your First Chatbot Using AI in Just 30 Minutes

How to Build Your First Chatbot Using AI in Just 30 Minutes Building a chatbot can feel like an ambitious project, especially if you're not a coding wizard. But here’s the kicker:

Jul 20, 20264 min read