Getting started overview

To begin using AI For Thai's language processing capabilities, developers need to complete a series of steps centered on account creation, API key retrieval, and initial client setup. This process ensures secure access to the platform's services, which include features like word segmentation, sentiment analysis, and machine translation for the Thai language. The primary goal of this guide is to enable a developer to send their first successful API request to an AI For Thai endpoint, validating their setup and connectivity.

The core workflow involves registering for an account, navigating to the developer dashboard to locate the API key, and then using this key in a programmatic request. AI For Thai provides SDKs for Python and JavaScript, facilitating integration into common development environments. This guide will walk through the necessary setup steps, offering practical examples for these languages.

Quick Reference: AI For Thai Getting Started

Step What to Do Where
1. Account Creation Register for a new AI For Thai account. AI For Thai homepage
2. API Key Retrieval Log in and find your unique API key in the dashboard. AI For Thai Developer Dashboard
3. Environment Setup Install necessary SDKs (Python or JavaScript). Local development environment
4. First API Call Construct and execute a request using your API key. Code editor (Python/JavaScript)
5. Verify Response Check the API response for success and expected data. Console output

Create an account and get keys

Accessing AI For Thai APIs requires a registered account and an associated API key. This key authenticates your requests and links them to your usage quotas. AI For Thai offers a free tier for non-commercial use, allowing up to 1000 requests per month for most APIs, suitable for initial testing and development.

  1. Navigate to the AI For Thai Homepage: Open your web browser and go to the official AI For Thai website.
  2. Register for an Account: Look for a "Sign Up" or "Register" button. You will typically be prompted to provide an email address, create a password, and agree to the terms of service. Follow the on-screen instructions to complete the registration process. An email verification step may be required.
  3. Log In to Your Account: Once registered and verified, log in to your newly created account using your credentials.
  4. Locate Your API Key: After logging in, navigate to the developer dashboard or a section often labeled "API Keys," "My Applications," or "Settings." Your unique API key will be displayed here. It is critical to treat this key as sensitive information, similar to a password, to prevent unauthorized access to your account and services.
  5. Copy Your API Key: Copy the displayed API key. This key will be used in the authorization header or as a query parameter in your API requests. For security best practices, consider storing your API key in environment variables rather than hardcoding it directly into your application's source code. This practice is recommended by various security guidelines, including those for managing AWS access keys, which apply broadly to API key management.

Your first request

With your API key in hand, you can now make your first call to an AI For Thai API. This example will demonstrate how to use the "Word Segmentation" (tokenize) API, a common starting point for Thai language processing.

The API endpoint for word segmentation is typically https://api.aiforthai.in.th/tokenize. Requests are generally sent as POST requests with a JSON body containing the text to be processed and the API key in the HTTP header for authentication.

Python Example

Before running the Python example, ensure you have the requests library installed:

pip install requests

Then, create a Python file (e.g., first_request.py) and add the following code:

import requests
import json
import os

# It is recommended to store your API key in an environment variable
# For demonstration, you can replace os.getenv with your actual key, but avoid in production
API_KEY = os.getenv("AIFORTHAI_API_KEY", "YOUR_AIFORTHAI_API_KEY_HERE")

url = "https://api.aiforthai.in.th/tokenize"
headers = {
    "Apikey": API_KEY,
    "Content-Type": "application/json"
}
data = {
    "text": "สวัสดีประเทศไทย"
}

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    
    response_json = response.json()
    print("API Response:")
    print(json.dumps(response_json, indent=2, ensure_ascii=False))

except requests.exceptions.HTTPError as errh:
    print (f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print (f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print (f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print (f"Something Else: {err}")

Replace "YOUR_AIFORTHAI_API_KEY_HERE" with the API key you retrieved from your dashboard. For production use, configure AIFORTHAI_API_KEY as an environment variable.

JavaScript Example (Node.js)

For the JavaScript example, you'll need Node.js installed and a package manager like npm or yarn. Create a new directory, initialize a Node.js project, and install the axios library:

mkdir aiforthai-js-example
cd aiforthai-js-example
npm init -y
npm install axios dotenv

Then, create a file named .env in your project directory and add your API key:

AIFORTHAI_API_KEY=YOUR_AIFORTHAI_API_KEY_HERE

Next, create a JavaScript file (e.g., first_request.js) and add the following code:

require('dotenv').config();
const axios = require('axios');

const API_KEY = process.env.AIFORTHAI_API_KEY;

if (!API_KEY) {
  console.error('Error: AIFORTHAI_API_KEY is not set in environment variables or .env file.');
  process.exit(1);
}

const url = "https://api.aiforthai.in.th/tokenize";
const headers = {
    "Apikey": API_KEY,
    "Content-Type": "application/json"
};
const data = {
    "text": "สวัสดีประเทศไทย"
};

axios.post(url, data, { headers })
    .then(response => {
        console.log("API Response:");
        console.log(JSON.stringify(response.data, null, 2));
    })
    .catch(error => {
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            console.error("Error Response Data:", error.response.data);
            console.error("Error Response Status:", error.response.status);
            console.error("Error Response Headers:", error.response.headers);
        } else if (error.request) {
            // The request was made but no response was received
            console.error("Error Request:", error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.error("Error Message:", error.message);
        }
        console.error("Error Config:", error.config);
    });

Execute the JavaScript code from your terminal:

node first_request.js

A successful response for both examples will show the segmented Thai text, typically in an array format.

Common next steps

After successfully making your first API call, you can explore other functionalities offered by AI For Thai. The platform provides a range of services beyond basic word segmentation.

  • Explore Other APIs: Consult the AI For Thai API reference for endpoints covering Part-of-Speech Tagging, Named Entity Recognition, Sentiment Analysis, Text Summarization, Machine Translation, and Speech applications. Each API serves a specific natural language processing task for the Thai language.
  • Integrate into Applications: Begin integrating AI For Thai services into your own applications, chatbots, or data processing pipelines. Consider how these APIs can enhance user experience or automate language-related tasks.
  • Review Pricing and Usage: Understand the pricing structure and monitor your API usage through the AI For Thai dashboard. This ensures your application stays within your chosen plan's limits, especially if moving beyond the free tier for commercial use.
  • Advanced Features and Customization: Depending on your needs, investigate any advanced features like custom model training or specific configurations mentioned in the official documentation. For complex applications, understanding how to handle rate limits and error conditions effectively is crucial, as detailed in general API error handling guidelines.
  • Community and Support: Engage with the AI For Thai community or support channels if you encounter complex issues or have specific implementation questions.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps for frequent problems:

  • Invalid API Key (401 Unauthorized):
    • Verify Key: Double-check that your API key is correctly copied from the AI For Thai dashboard and that there are no leading or trailing spaces.
    • Header Name: Ensure the header key is exactly Apikey (case-sensitive as specified in AI For Thai's documentation) and not API-Key or X-API-Key.
    • Environment Variable: If using environment variables, confirm they are loaded correctly in your execution environment.
  • Missing or Malformed Request Body (400 Bad Request):
    • JSON Format: Ensure your request body is valid JSON. Use a JSON validator if unsure.
    • Required Fields: Check that all required fields (e.g., text for the tokenize API) are present and correctly formatted according to the AI For Thai API reference.
    • Content-Type Header: Confirm the Content-Type header is set to application/json.
  • Network Issues (Connection Errors, Timeouts):
    • Internet Connection: Verify your internet connection is stable.
    • Firewall/Proxy: If you are in a corporate network, firewalls or proxies might be blocking outbound requests to api.aiforthai.in.th. Consult your IT department.
    • API Status: Check the AI For Thai status page (if available) for any ongoing service disruptions.
  • Rate Limit Exceeded (429 Too Many Requests):
    • Free Tier Limits: If you are on the free tier, you might have exceeded the 1000 requests per month limit.
    • Commercial Plans: If on a paid plan, review your plan's specific rate limits.
    • Retry Logic: Implement exponential backoff for retrying requests, a common practice described in AWS API error retry strategies.
  • Server Errors (5xx Series):
    • These typically indicate an issue on the AI For Thai server side. Report the issue to AI For Thai support with details of your request and the error message.

For persistent issues, refer to the comprehensive AI For Thai official documentation or contact their support channels.