Ai Coding Tools

How to Create an AI-Powered REST API in Under 2 Hours

By BTW Team3 min read

How to Create an AI-Powered REST API in Under 2 Hours

Building an AI-powered REST API might sound like a daunting task, especially if you’re a solo founder or indie hacker trying to juggle multiple projects. But I’m here to tell you that it doesn’t have to be. In fact, with the right tools and a clear plan, you can get it done in under two hours. Let’s dive into how to make this happen!

Prerequisites: What You Need Before You Start

Before we jump into the actual building process, make sure you have the following:

  1. Basic knowledge of REST APIs: Understanding concepts like endpoints, methods (GET, POST, etc.), and responses will be beneficial.
  2. A code editor: Visual Studio Code or any other IDE you prefer.
  3. Node.js installed: Ensure you have Node.js (v14 or later) installed on your machine.
  4. An OpenAI API key: Sign up at OpenAI and get your API key for AI functionalities.
  5. Postman or similar tool: For testing your API endpoints.

Step 1: Set Up Your Project (15 Minutes)

  1. Create a new directory for your project:

    mkdir ai-rest-api
    cd ai-rest-api
    
  2. Initialize a new Node.js project:

    npm init -y
    
  3. Install necessary dependencies:

    npm install express axios body-parser dotenv
    
  4. Create a .env file and add your OpenAI API key:

    OPENAI_API_KEY=your_openai_api_key_here
    

Step 2: Create the Server (30 Minutes)

  1. Create an index.js file:

    const express = require('express');
    const bodyParser = require('body-parser');
    const axios = require('axios');
    require('dotenv').config();
    
    const app = express();
    app.use(bodyParser.json());
    
    const PORT = process.env.PORT || 3000;
    
    app.post('/api/generate', async (req, res) => {
        const { prompt } = req.body;
        try {
            const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
                prompt,
                max_tokens: 50,
            }, {
                headers: {
                    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                    'Content-Type': 'application/json'
                }
            });
            res.json(response.data);
        } catch (error) {
            res.status(500).send(error.message);
        }
    });
    
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    
  2. Run your server:

    node index.js
    

Step 3: Test Your API (15 Minutes)

  1. Open Postman and create a new POST request to http://localhost:3000/api/generate.
  2. In the body, select JSON and enter:
    {
        "prompt": "Write a function to calculate the factorial of a number."
    }
    
  3. Send the request and you should receive a response with the generated code.

Step 4: Handling Errors (15 Minutes)

To make your API more robust, implement error handling. Update your index.js file to include more detailed error messages, and ensure you handle edge cases like missing prompts or invalid requests.

Troubleshooting: What Could Go Wrong

  • API key issues: Make sure your API key is correct and has the necessary permissions.
  • CORS errors: If you're accessing the API from a browser, you might run into CORS issues. Consider using the cors package to handle this.
  • Network issues: Ensure your server is running and that you have internet access to reach the OpenAI API.

What's Next: Expanding Your API

Now that you have a basic AI-powered REST API, consider adding more features:

  • Authentication: Secure your API with token-based authentication.
  • Rate limiting: Prevent abuse by limiting the number of requests a user can make.
  • Documentation: Use tools like Swagger to document your API.

Conclusion: Start Here

Creating an AI-powered REST API doesn’t have to be a lengthy process. With just a few tools and the steps outlined, you can have a functional API in under two hours. Start with the basics and expand as you grow more comfortable with the technology.

What We Actually Use

In our experience, we use Express for our backend, Axios for making requests, and OpenAI for AI functionalities. We've tried other frameworks, but Express offers the simplicity and speed we need for rapid development.

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 AI Coding Tools That Will Drastically Reduce Your Debugging Time

10 AI Coding Tools That Will Drastically Reduce Your Debugging Time As a developer, whether you're just starting out or have years of experience, debugging can feel like a neverend

Oct 16, 20265 min read
Ai Coding Tools

10 Common Mistakes When Integrating AI Coding Tools into Your Workflow

10 Common Mistakes When Integrating AI Coding Tools into Your Workflow As developers, we’re always on the lookout for ways to streamline our workflow and boost productivity. Enter

Oct 14, 20264 min read
Ai Coding Tools

5 Myths About AI Coding Tools That Could Hurt Your Development Process

5 Myths About AI Coding Tools That Could Hurt Your Development Process As a solo founder or indie hacker, you might be lured by the promises of AI coding tools that claim to simpli

Oct 13, 20264 min read
Ai Coding Tools

5 Common Mistakes Developers Make When Using AI Coding Tools in 2026

5 Common Mistakes Developers Make When Using AI Coding Tools in 2026 As AI coding tools have become an integral part of a developer's toolkit in 2026, many are still stumbling over

Oct 12, 20264 min read
Ai Coding Tools

5 Myths About AI Coding Tools: What Every Developer Should Know in 2026

5 Myths About AI Coding Tools: What Every Developer Should Know in 2026 As we dive into 2026, the landscape of AI coding tools has evolved significantly, yet many developers still

Oct 11, 20263 min read
Ai Coding Tools

Why AI Coding Assistants Are Overrated for Beginners in 2026

Why AI Coding Assistants Are Overrated for Beginners in 2026 As a solo founder or indie hacker, it’s tempting to think that AI coding assistants are the silver bullet to jumpstart

Oct 10, 20263 min read