Authentication overview

Authentication for AI For Thai APIs is a prerequisite for interacting with its services, which include functions such as Thai word segmentation, named entity recognition, and machine translation. The primary method for authenticating API requests is through the use of an API key. This key serves as a unique identifier and credential, granting access to the specific services and usage quotas associated with your developer account.

All interactions with AI For Thai's API endpoints are expected to occur over HTTPS to ensure the confidentiality and integrity of data in transit. The API key must be included with every request, typically within a designated HTTP header. Proper management and protection of this API key are essential for maintaining the security of your applications and preventing unauthorized access to your AI For Thai account and resources.

Supported authentication methods

AI For Thai primarily supports API key authentication for accessing its services. This method is suitable for most application-to-application communication where a direct, server-side integration is performed. The API key acts as a secret token that clients present to the API gateway to prove their identity and authorization.

Method Description When to Use Security Level
API Key A unique, secret string passed in the x-api-key HTTP header. Server-side applications, backend services, script-based integrations. Moderate (dependent on key secrecy)

While API keys are straightforward to implement, their security relies heavily on keeping them confidential. They should never be exposed in client-side code, mobile applications, or public repositories. For environments requiring more granular access control or user-specific authorization flows, alternative methods like OAuth 2.0 are often employed by other platforms, but AI For Thai's current model focuses on the simplicity and directness of API keys for developer integration.

Getting your credentials

To obtain the necessary API key for authenticating with AI For Thai, you must first register for a developer account on their official website. The process generally involves the following steps:

  1. Account Registration: Navigate to the AI For Thai homepage and sign up for a new account. This typically requires providing an email address and creating a password.
  2. Developer Portal Access: Once registered and logged in, you will gain access to the developer portal or dashboard. This portal is the central hub for managing your applications, monitoring usage, and accessing API keys.
  3. API Key Generation: Within the developer portal, locate the section dedicated to API keys or credentials. There will usually be an option to generate a new API key. Upon generation, the key (a long alphanumeric string) will be displayed.
  4. Key Storage: Immediately copy and securely store your API key. It is crucial to treat this key as a sensitive secret. AI For Thai's documentation advises against hardcoding keys directly into source code or committing them to version control systems.
  5. Usage Tiers: Be aware that AI For Thai offers a free tier for non-commercial use, which typically provides a limited number of requests per month. Commercial use or higher request volumes will require subscribing to a paid plan, which will also utilize the same API key for authentication.

If you lose your API key or suspect it has been compromised, you should generate a new one through the developer portal and revoke the old key if that option is available. This ensures that the compromised key can no longer be used to access your account's resources.

Authenticated request example

After obtaining your API key, you can include it in your API requests to AI For Thai's endpoints. The key is typically sent in the x-api-key HTTP header. Below are examples demonstrating how to make an authenticated request using Python and JavaScript, which are the primary language examples provided by AI For Thai.

Python Example

This Python example demonstrates how to call the AI For Thai Word Segmentation API with your API key.


import requests

API_KEY = "YOUR_API_KEY"
TEXT_TO_SEGMENT = "สวัสดีครับ"

headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
}

url = "https://api.aiforthai.in.th/tokenize"
payload = {"text": TEXT_TO_SEGMENT}

try:
    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status() # Raise an exception for HTTP errors
    print("Response:", response.json())
except requests.exceptions.HTTPError as e:
    print(f"HTTP error occurred: {e}")
except requests.exceptions.ConnectionError as e:
    print(f"Connection error occurred: {e}")
except requests.exceptions.Timeout as e:
    print(f"Timeout error occurred: {e}")
except requests.exceptions.RequestException as e:
    print(f"An unexpected error occurred: {e}")

JavaScript (Node.js) Example

This JavaScript example uses fetch in a Node.js environment to make an authenticated request to the same Word Segmentation API.


const fetch = require('node-fetch'); // For Node.js, install with npm install node-fetch

const API_KEY = "YOUR_API_KEY";
const TEXT_TO_SEGMENT = "สวัสดีครับ";

const headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
};

const url = "https://api.aiforthai.in.th/tokenize";
const payload = {
    text: TEXT_TO_SEGMENT
};

async function segmentText() {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log("Response:", data);
    } catch (error) {
        console.error("Error during API call:", error);
    }
}

segmentText();

Remember to replace "YOUR_API_KEY" with your actual API key obtained from the AI For Thai developer portal. These examples illustrate the fundamental pattern for including the API key in the request headers.

Security best practices

Securing your API keys and ensuring the integrity of your API interactions are critical for protecting your application and your AI For Thai account. Adhere to these best practices:

  • Keep API Keys Confidential: Treat your API key as a sensitive secret. Never hardcode it directly into client-side code (e.g., JavaScript in a browser), mobile applications, or publicly accessible repositories.
  • Use Environment Variables: Store API keys in environment variables on your server or development machine. This prevents them from being exposed in your codebase and makes it easier to manage different keys for various environments (development, staging, production). For instance, in Node.js, you might use process.env.AIFORTHAI_API_KEY.
  • Implement Server-Side Proxies: For client-side applications that need to access AI For Thai APIs, route requests through your own backend server. The backend server can then securely add the API key before forwarding the request to AI For Thai. This prevents the API key from ever being exposed to the client.
  • Restrict IP Addresses (if available): If AI For Thai's developer portal offers the capability to restrict API key usage to specific IP addresses, leverage this feature. This adds an extra layer of security, ensuring that even if a key is compromised, it can only be used from authorized server locations.
  • Monitor API Usage: Regularly monitor your API usage through the AI For Thai developer dashboard. Unexpected spikes in usage could indicate a compromised key or unauthorized access.
  • Rotate API Keys: Periodically rotate your API keys. This involves generating a new key, updating your applications to use the new key, and then revoking the old key. This practice limits the window of exposure if a key is ever compromised.
  • Secure Your Development Environment: Ensure that your development machines and build pipelines are secure. Unauthorized access to these environments could lead to the exposure of API keys and other sensitive credentials.
  • Use HTTPS/TLS: Always ensure that all communications with the AI For Thai API are conducted over HTTPS (TLS). This encrypts the data in transit, protecting your API key and request/response payloads from eavesdropping. The Transport Layer Security (TLS) protocol is essential for secure network communication.
  • Error Handling: Implement robust error handling in your application. This helps in gracefully managing API errors and can prevent unintended information disclosure if an API call fails.

By following these best practices, developers can significantly enhance the security posture of applications integrating with AI For Thai APIs, safeguarding both their data and their API access.