Skip to main content

What is an AI API? A Complete Beginner's Guide with Hands-On Tutorial

· 10 min read
Kobkrit Viriyayudhakorn
CEO @ iApp Technology

By Dr. Kobkrit Viriyayudhakorn, CEO & Founder, iApp Technology

Have you ever wondered how applications like Google Translate, face filters on Instagram, or voice assistants like Siri work? Behind these amazing features lies a powerful technology called AI API. In this guide, we'll break down exactly what an AI API is, how it works, and most importantly - you'll build your first AI-powered application by the end of this article!

AI API Beginner's Guide

Part 1: Understanding the Basics

What is an API?

Before diving into AI APIs, let's understand what an API is.

API stands for Application Programming Interface. Think of it as a waiter in a restaurant:

  1. You (the customer) want to order food
  2. The kitchen can prepare the food
  3. The waiter (API) takes your order to the kitchen and brings back your food

In the tech world:

  • You = Your application (website, mobile app, software)
  • The kitchen = A server with special capabilities
  • The waiter (API) = The interface that lets you communicate with that server

API works like a waiter - taking requests to the kitchen (server) and returning responses

Real-World API Examples

You use APIs every day without realizing it:

When you...You're using...
Check weather on your phoneWeather API
Pay with credit card onlinePayment API (Stripe, PayPal)
Login with Google/FacebookOAuth API
See a map in an appGoogle Maps API
Share to social mediaSocial Media APIs

What is an AI API?

An AI API is an API that provides artificial intelligence capabilities as a service. Instead of building complex AI models yourself (which requires expertise, data, and computing power), you simply send a request to an AI API and receive intelligent results.

AI API = AI as a Service

Without AI API vs With AI API - The difference between building AI yourself and using AI APIs

Types of AI APIs

CategoryWhat it doesExamples
Computer VisionAnalyzes images and videosOCR, Face Detection, Object Recognition
Natural Language Processing (NLP)Understands and generates textTranslation, Sentiment Analysis, Chatbots
SpeechConverts speech to text and vice versaSpeech-to-Text, Text-to-Speech
Generative AICreates new contentChatGPT, Image Generation, Code Generation

How Does an AI API Work?

Let's understand the complete flow of an AI API request:

Step-by-Step Flow

AI API Request Flow - From preparing request to receiving response

The Request-Response Cycle

1. Request Components

Every AI API request typically contains:

{
// WHERE to send the request
"url": "https://api.iapp.co.th/thai-national-id-card/v3/front",

// HOW to authenticate
"headers": {
"apikey": "your-secret-api-key"
},

// WHAT to process
"body": {
"file": "<your image or text data>"
}
}

2. Response Components

The AI API returns a structured response:

{
// The AI's analysis results
"result": {
"id_number": "1234567890123",
"name_th": "นายทดสอบ ตัวอย่าง",
"name_en": "Mr. Test Example",
"date_of_birth": "01 Jan 1990"
},

// How confident the AI is
"confidence": 0.98,

// Processing information
"processing_time_ms": 245
}

Part 2: Hands-On Tutorial - Your First AI API Call

Now let's build something real! We'll use iApp Technology's Thai AI APIs to create your first AI-powered application.

What We'll Build

We'll create a simple application that:

  1. Analyzes sentiment of Thai text (positive/negative/neutral)
  2. Extracts information from a Thai ID card image

Prerequisites

  • Basic understanding of any programming language
  • A computer with internet connection
  • 15 minutes of your time

Step 1: Get Your Free API Key

  1. Visit https://iapp.co.th/register
  2. Create a free account
  3. Go to API Keys section
  4. Click Create New API Key
  5. Copy your API key (save it securely!)
Free Credits

New accounts receive free credits to test the APIs!

Step 2: Your First API Call - Sentiment Analysis

Let's analyze the sentiment of Thai text. This API determines if text is positive, negative, or neutral.

Using cURL (Terminal/Command Line)

curl -X POST "https://api.iapp.co.th/sentimental-analysis/predict" \
-H "apikey: YOUR_API_KEY" \
-d "text=วันนี้อากาศดีมาก ฉันมีความสุขจัง"

Using Python

import requests

# Configuration
API_KEY = "YOUR_API_KEY" # Replace with your actual API key
API_URL = "https://api.iapp.co.th/sentimental-analysis/predict"

# The Thai text to analyze
thai_text = "วันนี้อากาศดีมาก ฉันมีความสุขจัง" # "The weather is great today, I'm so happy"

# Make the API request
response = requests.post(
API_URL,
headers={"apikey": API_KEY},
params={"text": thai_text}
)

# Parse the response
result = response.json()

# Display results
print(f"Text: {thai_text}")
print(f"Sentiment: {result['label']}") # pos, neg, or neu
print(f"Confidence: {result['score']:.2%}")

Expected Output:

Text: วันนี้อากาศดีมาก ฉันมีความสุขจัง
Sentiment: pos
Confidence: 89.45%

Using JavaScript (Node.js)

const axios = require('axios');

// Configuration
const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const API_URL = 'https://api.iapp.co.th/sentimental-analysis/predict';

// The Thai text to analyze
const thaiText = 'วันนี้อากาศดีมาก ฉันมีความสุขจัง';

// Make the API request
async function analyzeSentiment() {
try {
const response = await axios.post(
`${API_URL}?text=${encodeURIComponent(thaiText)}`,
{},
{
headers: { 'apikey': API_KEY }
}
);

console.log(`Text: ${thaiText}`);
console.log(`Sentiment: ${response.data.label}`);
console.log(`Confidence: ${(response.data.score * 100).toFixed(2)}%`);
} catch (error) {
console.error('Error:', error.message);
}
}

analyzeSentiment();

Using JavaScript (Browser/Frontend)

<!DOCTYPE html>
<html>
<head>
<title>Thai Sentiment Analyzer</title>
</head>
<body>
<h1>Thai Sentiment Analyzer</h1>
<textarea id="textInput" placeholder="Enter Thai text..."></textarea>
<button onclick="analyze()">Analyze Sentiment</button>
<div id="result"></div>

<script>
async function analyze() {
const text = document.getElementById('textInput').value;
const API_KEY = 'YOUR_API_KEY';

const response = await fetch(
`https://api.iapp.co.th/sentimental-analysis/predict?text=${encodeURIComponent(text)}`,
{
method: 'POST',
headers: { 'apikey': API_KEY }
}
);

const data = await response.json();

const sentimentEmoji = {
'pos': '😊 Positive',
'neg': '😢 Negative',
'neu': '😐 Neutral'
};

document.getElementById('result').innerHTML = `
<p>Sentiment: ${sentimentEmoji[data.label]}</p>
<p>Confidence: ${(data.score * 100).toFixed(2)}%</p>
`;
}
</script>
</body>
</html>

Step 3: OCR API - Extract Data from Thai ID Card

Now let's try something more advanced - extracting information from a Thai National ID Card image.

Using Python

import requests

# Configuration
API_KEY = "YOUR_API_KEY"
API_URL = "https://api.iapp.co.th/thai-national-id-card/v3/front"

# Path to your ID card image
image_path = "thai_id_card.jpg"

# Prepare the file
with open(image_path, 'rb') as image_file:
files = {'file': image_file}
headers = {'apikey': API_KEY}

# Make the API request
response = requests.post(API_URL, headers=headers, files=files)

# Parse and display results
result = response.json()

print("=== Thai ID Card OCR Results ===")
print(f"ID Number: {result.get('id_number', 'N/A')}")
print(f"Thai Name: {result.get('name_th', 'N/A')}")
print(f"English Name: {result.get('name_en', 'N/A')}")
print(f"Date of Birth: {result.get('date_of_birth', 'N/A')}")
print(f"Address: {result.get('address', 'N/A')}")

Expected Output:

=== Thai ID Card OCR Results ===
ID Number: 1-2345-67890-12-3
Thai Name: นาย ทดสอบ ตัวอย่าง
English Name: Mr. Test Example
Date of Birth: 01 Jan 1990
Address: 123 ถนนสุขุมวิท แขวงคลองตัน เขตวัฒนา กรุงเทพฯ 10110

Using JavaScript (Node.js)

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

// Configuration
const API_KEY = 'YOUR_API_KEY';
const API_URL = 'https://api.iapp.co.th/thai-national-id-card/v3/front';

async function extractIdCard() {
// Create form data with image
const formData = new FormData();
formData.append('file', fs.createReadStream('thai_id_card.jpg'));

try {
const response = await axios.post(API_URL, formData, {
headers: {
'apikey': API_KEY,
...formData.getHeaders()
}
});

const result = response.data;

console.log('=== Thai ID Card OCR Results ===');
console.log(`ID Number: ${result.id_number || 'N/A'}`);
console.log(`Thai Name: ${result.name_th || 'N/A'}`);
console.log(`English Name: ${result.name_en || 'N/A'}`);
console.log(`Date of Birth: ${result.date_of_birth || 'N/A'}`);
} catch (error) {
console.error('Error:', error.message);
}
}

extractIdCard();

Part 3: Best Practices for Using AI APIs

1. Secure Your API Key

# ❌ BAD - Never hardcode API keys
API_KEY = "sk-1234567890abcdef"

# ✅ GOOD - Use environment variables
import os
API_KEY = os.environ.get('IAPP_API_KEY')

2. Handle Errors Gracefully

import requests

def analyze_sentiment(text):
try:
response = requests.post(
API_URL,
headers={"apikey": API_KEY},
params={"text": text},
timeout=30 # Set timeout
)

# Check for HTTP errors
response.raise_for_status()

return response.json()

except requests.exceptions.Timeout:
print("Request timed out. Please try again.")
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("Invalid API key")
elif e.response.status_code == 429:
print("Rate limit exceeded. Please wait.")
else:
print(f"HTTP Error: {e}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")

return None

3. Implement Retry Logic

import time
import requests

def api_call_with_retry(url, headers, data, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # Exponential backoff
print(f"Attempt {attempt + 1} failed. Retrying in {wait_time}s...")
time.sleep(wait_time)
else:
raise e

4. Cache Results When Appropriate

from functools import lru_cache
import hashlib

@lru_cache(maxsize=100)
def cached_sentiment_analysis(text_hash):
# This caches results for identical inputs
return analyze_sentiment_internal(text_hash)

def analyze_sentiment(text):
text_hash = hashlib.md5(text.encode()).hexdigest()
return cached_sentiment_analysis(text_hash)

Part 4: Common AI API Use Cases

E-KYC (Electronic Know Your Customer)

# Verify customer identity by comparing ID card photo with selfie
def verify_identity(id_card_image, selfie_image):
# Step 1: Extract face from ID card
id_face = extract_face(id_card_image)

# Step 2: Extract face from selfie
selfie_face = extract_face(selfie_image)

# Step 3: Compare faces
match_result = compare_faces(id_face, selfie_face)

return match_result['is_same_person'], match_result['confidence']

Customer Feedback Analysis

# Analyze customer reviews at scale
def analyze_customer_feedback(reviews):
results = {
'positive': 0,
'negative': 0,
'neutral': 0,
'issues': []
}

for review in reviews:
sentiment = analyze_sentiment(review['text'])
results[sentiment['label']] += 1

if sentiment['label'] == 'neg':
results['issues'].append(review)

return results

Document Processing Automation

# Automate invoice processing
def process_invoice(invoice_image):
# Extract text from invoice using OCR
ocr_result = extract_text(invoice_image)

# Parse structured data
invoice_data = {
'invoice_number': extract_field(ocr_result, 'invoice_number'),
'date': extract_field(ocr_result, 'date'),
'total': extract_field(ocr_result, 'total'),
'items': extract_line_items(ocr_result)
}

return invoice_data

Part 5: Choosing the Right AI API Provider

Key Factors to Consider

FactorQuestions to Ask
AccuracyWhat's the accuracy rate? Is it optimized for your language/use case?
SpeedWhat's the average response time?
PricingPay-per-use or subscription? What are the rates?
SupportIs local language support available?
SecurityIs data encrypted? GDPR/PDPA compliant?
ReliabilityWhat's the uptime SLA?

Why Choose iApp Technology

FeatureiApp Technology
Thai Language OptimizationAI models specifically trained for Thai
Local SupportThai-speaking support team
CompliancePDPA & GDPR compliant
CertificationsISO 29110, iBeta PAD Level 1 & 2
PricingCompetitive pay-per-use pricing
Free TrialFree credits to test APIs

Summary

In this guide, you've learned:

  1. What an API is - A communication interface between applications
  2. What an AI API is - AI capabilities delivered as a service
  3. How AI APIs work - The request-response cycle
  4. How to make your first AI API call - With practical code examples
  5. Best practices - Security, error handling, and optimization
  6. Common use cases - E-KYC, sentiment analysis, document processing

Your Next Steps

  1. Sign up for a free iApp account at iapp.co.th/register
  2. Get your API key from the dashboard
  3. Try the examples in this tutorial
  4. Explore more APIs in our documentation
  5. Build something amazing!

Resources


About the Author

Dr. Kobkrit Viriyayudhakorn is the CEO and Founder of iApp Technology, Thailand's leading AI company. With over 15 years of experience in artificial intelligence and natural language processing, Dr. Kobkrit is passionate about making AI accessible to developers and businesses of all sizes.


References

  1. IBM Developer, "What is an API?", 2024
  2. Google Cloud, "Machine Learning APIs", 2024
  3. AWS, "What is a REST API?", 2024
  4. iApp Technology, "API Documentation", 2025
  5. Postman, "The State of the API Report", 2024