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

10 Common Mistakes When Using AI Coding Tools for Beginners

10 Common Mistakes When Using AI Coding Tools for Beginners As a beginner in coding, diving into AI coding tools can feel like a doubleedged sword. On one hand, these tools promise

Oct 8, 20264 min read
Ai Coding Tools

5 Common Misconceptions About AI Coding Tools and Why They Hold You Back

5 Common Misconceptions About AI Coding Tools and Why They Hold You Back As a solo founder or indie hacker, you might be considering leveraging AI coding tools to boost your produc

Oct 7, 20264 min read
Ai Coding Tools

5 Common Misconceptions About AI Coding Tools That Will Hurt Your Learning

5 Common Misconceptions About AI Coding Tools That Will Hurt Your Learning As a beginner in coding, diving into the world of AI coding tools can feel like stepping into a futuristi

Oct 6, 20263 min read
Ai Coding Tools

10 AI Coding Tools Beginners Overlook in 2026

10 AI Coding Tools Beginners Overlook in 2026 As a beginner in coding, diving into the vast ocean of AI tools can feel overwhelming. While flashy tools often grab the spotlight, ma

Oct 6, 20265 min read
Ai Coding Tools

5 Common Misconceptions About AI Coding Tools That Beginners Believe

5 Common Misconceptions About AI Coding Tools That Beginners Believe As a solo founder or indie hacker, diving into the world of AI coding tools can feel overwhelming, especially i

Oct 5, 20263 min read
Ai Coding Tools

5 Mistakes Every Beginner Makes When Using AI Coding Tools

5 Mistakes Every Beginner Makes When Using AI Coding Tools As a solo founder or indie hacker diving into the world of AI coding tools, it’s easy to get swept up in the excitement o

Oct 4, 20264 min read