Getting started overview

Integrating with the Detect Language API involves a sequence of steps designed to get you from account creation to a functional language detection call. This guide outlines the essential procedures, including signing up, obtaining API credentials, and executing your initial API request. Understanding these steps is fundamental for leveraging the API's capabilities, whether for processing user input or automating content classification.

The Detect Language API primarily offers a single endpoint for text or batch text detection. The API supports various programming languages through official SDKs, simplifying the integration process by abstracting direct HTTP request handling. For those preferring direct HTTP interactions, the API follows RESTful principles, accepting JSON payloads and returning JSON responses, which is a common pattern for web services RESTful API design principles.

Before making any API calls, you will need to register an account and generate an API key. This key authenticates your requests and links them to your usage allowance, including the Detect Language free tier of 5,000 detections per day.

Quick Reference Steps

Step What to Do Where
1. Sign Up Create a Detect Language account. Detect Language homepage
2. Get API Key Locate your unique API key in your account dashboard. Detect Language dashboard (after signup)
3. Choose Method Decide between an official SDK or a direct HTTP request. Detect Language documentation
4. Make Request Send a text string to the API for language detection. Your development environment
5. Process Response Parse the JSON response to extract language information. Your development environment

Create an account and get keys

To begin using the Detect Language API, the first step is to create a user account. This process typically involves providing an email address and setting a password. Upon successful registration, you will gain access to your personal dashboard.

  1. Navigate to the Detect Language website: Go to the Detect Language homepage.
  2. Sign Up: Look for a 'Sign Up' or 'Get Started' button and follow the prompts to create a new account. This usually requires an email address and a password.
  3. Verify Email (if required): Some services send a verification email to confirm your account. Check your inbox and spam folder for a verification link and click it to activate your account.
  4. Access Dashboard: Once logged in, you will be directed to your account dashboard. This is where you manage your subscription, view usage statistics, and find your API key.
  5. Locate API Key: Your unique API key will be prominently displayed within your dashboard, often in a section labeled 'API Key' or 'Credentials'. This key is a string of alphanumeric characters that authenticates your requests to the Detect Language API. Keep this key confidential, as it grants access to your account's API usage. The official Detect Language documentation provides further details on API key management.

It is crucial to handle your API key securely. Avoid embedding it directly into client-side code that could be publicly exposed, and use environment variables or a secure configuration management system in server-side applications. For applications running in browser environments, consider proxying requests through your own backend to keep the API key server-side.

Your first request

After obtaining your API key, you can make your first request to the Detect Language API. This example demonstrates how to detect the language of a simple text string using a direct HTTP POST request. While SDKs are available for various languages, understanding the direct HTTP interaction provides a foundational understanding.

API Endpoint

The primary endpoint for language detection is usually a variation of https://ws.detectlanguage.com/0.2/detect.

Request Structure

The API expects a POST request with a JSON body containing the text to be analyzed and your API key. The API key can also be passed as a query parameter or an X-Detectlanguage-Api-Key HTTP header.

Example JSON Request Body:

{
  "q": "Hello, world! How are you?"
}

Example curl Request:

This curl command sends a request to the Detect Language API, including your API key in the header. Replace YOUR_API_KEY with the actual key from your dashboard.

curl -X POST \
  https://ws.detectlanguage.com/0.2/detect \
  -H "X-Detectlanguage-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"q": "Hello, world! How are you today?"}'

Expected JSON Response:

A successful response will return a JSON object containing detection results, including the detected language code, confidence score, and whether the result is reliable.

{
  "data": {
    "detections": [
      {
        "language": "en",
        "isReliable": true,
        "confidence": 10.0
      }
    ]
  }
}

Using an Official SDK (Python Example)

Detect Language provides official SDKs for several programming languages, including Python, PHP, and Node.js. Using an SDK can simplify the process by handling HTTP requests, JSON parsing, and error handling for you.

First, install the Python SDK:

pip install detectlanguage

Then, use the SDK in your Python code:

import detectlanguage

detectlanguage.configuration.api_key = "YOUR_API_KEY"

text = "Bonjour le monde! Comment ça va aujourd'hui?"

try:
    detections = detectlanguage.detect(text)
    for detection in detections:
        print(f"Language: {detection['language']}, Reliable: {detection['isReliable']}, Confidence: {detection['confidence']}")
except Exception as e:
    print(f"An error occurred: {e}")

This Python example initializes the Detect Language client with your API key and then calls the detect method with the input text. The result is a list of dictionaries, each representing a detected language and its associated metadata.

Common next steps

Once you have successfully made your first API call, you can explore more advanced features and integrate the API into your application workflows. Here are some common next steps:

  • Batch Detection: The Detect Language API supports sending multiple text strings in a single request, which can improve efficiency and reduce the number of API calls for applications processing large volumes of text. Consult the batch detection documentation for details on structuring these requests.
  • Language Hints: For texts that might be ambiguous or very short, you can provide hints to the API to improve detection accuracy. This is particularly useful in scenarios where you have some prior knowledge about the potential languages of the input.
  • Error Handling: Implement robust error handling in your application. The API returns standard HTTP status codes (e.g., 400 for bad request, 403 for forbidden, 500 for internal server error) along with detailed error messages in the JSON response body. Proper error handling ensures your application gracefully manages issues like invalid API keys or malformed requests.
  • Rate Limiting and Usage Monitoring: Be aware of the API's rate limits to avoid exceeding your quota, especially if you are on the free tier or a lower-paid plan. Monitor your API usage through your Detect Language dashboard to track your consumption and plan for potential scaling.
  • SDK Exploration: If you used a direct HTTP request for your first call, consider exploring the official SDK for your preferred programming language. SDKs often provide helper functions, manage authentication, and simplify interaction with the API, as demonstrated by the Python SDK example.
  • Integration with Other Services: Language detection is often a precursor to other actions. For example, you might integrate Detect Language with a translation API (like Google Cloud Translation API), a content moderation system, or a customer support routing platform to direct inquiries based on language.

Troubleshooting the first call

Encountering issues during your first API call is common. Here's a guide to troubleshoot some frequent problems:

  • Invalid API Key (HTTP 403 Forbidden):
    • Symptom: The API returns a 403 Forbidden status code and an error message indicating an invalid API key.
    • Solution: Double-check that you have copied your API key correctly from your Detect Language dashboard. Ensure there are no leading or trailing spaces. Verify that the key is included in the request headers (X-Detectlanguage-Api-Key) or as a query parameter, as specified in the Detect Language documentation.
  • Missing or Malformed Request Body (HTTP 400 Bad Request):
    • Symptom: The API responds with a 400 Bad Request status code, often with a message about invalid JSON or missing parameters.
    • Solution: Ensure your request body is valid JSON. For the language detection endpoint, the JSON body typically requires a q field containing the text to be detected. Check for syntax errors in your JSON (e.g., missing commas, unclosed quotes).
  • Rate Limit Exceeded (HTTP 429 Too Many Requests):
    • Symptom: You receive a 429 Too Many Requests status code.
    • Solution: This indicates you've surpassed your allowed number of requests within a given time frame (e.g., daily limit for the free tier). Wait for the rate limit to reset, or consider upgrading your Detect Language subscription plan if you require higher usage.
  • Network Connectivity Issues:
    • Symptom: Your application cannot connect to the API endpoint, resulting in network errors or timeouts.
    • Solution: Verify your internet connection. Check if there are any firewalls or proxy settings that might be blocking outbound requests to https://ws.detectlanguage.com. Ensure the API endpoint URL is spelled correctly.
  • Unexpected Response Format:
    • Symptom: The API returns a response, but it's not in the expected JSON format, or specific fields are missing.
    • Solution: Refer to the Detect Language API documentation on response format to confirm what a typical successful response should look like. Ensure your code is correctly parsing the JSON response.
  • SDK-Specific Errors:
    • Symptom: Errors originating from the SDK itself (e.g., detectlanguage.exceptions.DetectLanguageError in Python).
    • Solution: Consult the specific SDK's documentation or source code for common error patterns. Ensure your SDK is up-to-date. Often these errors wrap underlying API errors, so checking the inner exception or message can provide more context.