Ai Coding Tools

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

By BTW Team3 min read

Comparing tools? See the AI tools tested on the show.

In short

Step-by-step tutorial on creating a basic API using ChatGPT, perfect for those looking to enhance their coding skills quickly.

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.

Watch real AI builds every week

Built This Week is a weekly podcast where Jordan Metzner and Sam Nadler build something real with AI every episode, test new AI tools and talk with founders who build with AI.

See the tools

Watch real AI builds every week

Built This Week is a weekly podcast where Jordan Metzner and Sam Nadler build something real with AI every episode, test new AI tools and talk with founders who build with AI.

See the tools
Ai Coding Tools

3 AI Coding Tools That Are Overrated (and Why You Should Avoid Them)

3 AI Coding Tools That Are Overrated (and Why You Should Avoid Them) In the everevolving landscape of AI coding tools, it's easy to get swept up in the hype. As indie hackers and s

Nov 30, 20263 min read
Ai Coding Tools

5 Ways AI Coding Tools Can Accelerate Your MVP Development in 2026

5 Ways AI Coding Tools Can Accelerate Your MVP Development in 2026 In 2026, the landscape for indie hackers and solo founders has evolved significantly, especially with the advent

Nov 26, 20264 min read
Ai Coding Tools

5 AI Coding Tools That Make Legacy Code Feel Brand New in 2026

5 AI Coding Tools That Make Legacy Code Feel Brand New in 2026 If you’re a developer stuck maintaining legacy code, you know the frustration. It’s like navigating a maze blindfolde

Nov 23, 20264 min read
Ai Coding Tools

10 AI Coding Tools That Will Save You Hours of Debugging in 2026

10 AI Coding Tools That Will Save You Hours of Debugging in 2026 Debugging can feel like a neverending cycle of frustration. Whether you're a solo founder or an indie hacker, spend

Nov 18, 20265 min read
Ai Coding Tools

10 Common Mistakes When Using AI Coding Tools for MVP Development

10 Common Mistakes When Using AI Coding Tools for MVP Development As a founder in 2026, you’re likely aware that AI coding tools can significantly speed up the MVP development proc

Nov 16, 20264 min read
Ai Coding Tools

5 AI Coding Myths Every Beginner Developer Should Ditch in 2026

5 AI Coding Myths Every Beginner Developer Should Ditch in 2026 As a beginner developer, you’ve probably come across a ton of buzz surrounding AI coding tools. But with all the hyp

Nov 12, 20263 min read