ShahiTranslate

REST API Documentation

Overview

ShahiTranslate Pro provides a comprehensive REST API that allows programmatic access to translation features, enabling integration with external applications, mobile apps, and custom workflows.

API Base URL

`
https://yoursite.com/wp-json/shahitranslate/v1/
`

Authentication

Methods Supported

  1. Cookie Authentication (for logged-in users)
  2. Application Passwords (WordPress 5.6+)
  3. OAuth 1.0a (with OAuth plugin)
  4. JWT Tokens (with JWT Authentication plugin)
  5. Using Application Passwords

    Generate Password:

  6. Go to Users → Profile
  7. Scroll to “Application Passwords”
  8. Enter name: “API Access”
  9. Click “Add New Application Password”
  10. Copy generated password
  11. Making Authenticated Requests:
    `bash
    curl -X POST https://yoursite.com/wp-json/shahitranslate/v1/translate \
    -u “username:application_password” \
    -H “Content-Type: application/json” \
    -d ‘{“content”:”Hello World”,”language”:”es”}’
    `

    Using Nonce (for AJAX from same site)

    `javascript
    wp.apiFetch({
    path: ‘/shahitranslate/v1/translate’,
    method: ‘POST’,
    data: {
    content: ‘Hello World’,
    language: ‘es’
    }
    }).then(response => {
    console.log(response);
    });
    `

    Endpoints

    Languages

    Get Active Languages

    Endpoint: GET /shahitranslate/v1/languages

    Description: Retrieve list of active languages

    Authentication: None required

    Response:
    `json
    {
    “success”: true,
    “data”: [
    {
    “code”: “en”,
    “name”: “English”,
    “native_name”: “English”,
    “is_rtl”: false,
    “is_default”: true
    },
    {
    “code”: “es”,
    “name”: “Spanish”,
    “native_name”: “Español”,
    “is_rtl”: false,
    “is_default”: false
    },
    {
    “code”: “ar”,
    “name”: “Arabic”,
    “native_name”: “العربية”,
    “is_rtl”: true,
    “is_default”: false
    }
    ]
    }
    `

    Example:
    `bash
    curl https://yoursite.com/wp-json/shahitranslate/v1/languages
    `

    `javascript
    // JavaScript
    fetch(‘https://yoursite.com/wp-json/shahitranslate/v1/languages’)
    .then(response => response.json())
    .then(data => console.log(data));
    `

    `php
    // PHP
    $response = wpremoteget(‘https://yoursite.com/wp-json/shahitranslate/v1/languages’);
    $languages = jsondecode(wpremoteretrievebody($response), true);
    `

    Get Language Details

    Endpoint: GET /shahitranslate/v1/languages/{language_code}

    Parameters:

    • language_code (required): Language code (e.g., ‘es’, ‘fr’)
    • Response:
      `json
      {
      “success”: true,
      “data”: {
      “code”: “es”,
      “name”: “Spanish”,
      “native_name”: “Español”,
      “is_rtl”: false,
      “is_default”: false,
      “flag_url”: “https://yoursite.com/wp-content/plugins/shahitranslate-pro/assets/ShahiFlags/32/es.png”,
      “statistics”: {
      “total_translations”: 1234,
      “manual_translations”: 234,
      “automatic_translations”: 1000
      }
      }
      }
      `

      Translation

      Translate Content

      Endpoint: POST /shahitranslate/v1/translate

      Authentication: Required

      Parameters:

    • content (required, string): Content to translate
    • language (required, string): Target language code
    • source_language (optional, string): Source language code (auto-detected if not provided)
    • format (optional, string): ‘text’ or ‘html’ (default: ‘html’)
    • cache (optional, boolean): Use cached translation if available (default: true)
    • Request Body:
      `json
      {
      “content”: “Hello, how are you?”,
      “language”: “es”,
      “source_language”: “en”,
      “format”: “text”
      }
      `

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “original”: “Hello, how are you?”,
      “translated”: “Hola, ¿cómo estás?”,
      “source_language”: “en”,
      “target_language”: “es”,
      “method”: “automatic”,
      “cached”: false,
      “characters”: 19
      }
      }
      `

      Examples:

      `bash

      cURL

      curl -X POST https://yoursite.com/wp-json/shahitranslate/v1/translate \
      -u “username:app_password” \
      -H “Content-Type: application/json” \
      -d ‘{
      “content”: “Welcome to our website”,
      “language”: “es”
      }’
      `

      `javascript
      // JavaScript (using Fetch API)
      fetch(‘https://yoursite.com/wp-json/shahitranslate/v1/translate’, {
      method: ‘POST’,
      headers: {
      ‘Content-Type’: ‘application/json’,
      ‘Authorization’: ‘Basic ‘ + btoa(‘username:app_password’)
      },
      body: JSON.stringify({
      content: ‘Welcome to our website’,
      language: ‘es’
      })
      })
      .then(response => response.json())
      .then(data => console.log(data.data.translated));
      `

      `php
      // PHP
      $response = wpremotepost(‘https://yoursite.com/wp-json/shahitranslate/v1/translate’, [
      ‘headers’ => [
      ‘Authorization’ => ‘Basic ‘ . base64encode(‘username:apppassword’),
      ‘Content-Type’ => ‘application/json’
      ],
      ‘body’ => json_encode([
      ‘content’ => ‘Welcome to our website’,
      ‘language’ => ‘es’
      ])
      ]);

      $result = jsondecode(wpremoteretrievebody($response), true);
      echo $result[‘data’][‘translated’];
      `

      `python

      Python

      import requests
      from requests.auth import HTTPBasicAuth

      response = requests.post(
      ‘https://yoursite.com/wp-json/shahitranslate/v1/translate’,
      auth=HTTPBasicAuth(‘username’, ‘app_password’),
      json={
      ‘content’: ‘Welcome to our website’,
      ‘language’: ‘es’
      }
      )

      data = response.json()
      print(data[‘data’][‘translated’])
      `

      Batch Translate

      Endpoint: POST /shahitranslate/v1/translate/batch

      Authentication: Required

      Parameters:

    • items (required, array): Array of translation items
    • language (required, string): Target language code
    • source_language (optional, string): Source language code
    • Request Body:
      `json
      {
      “language”: “es”,
      “items”: [
      {
      “id”: “item1”,
      “content”: “Hello World”
      },
      {
      “id”: “item2”,
      “content”: “Welcome to our site”
      },
      {
      “id”: “item3”,
      “content”: “Contact Us”
      }
      ]
      }
      `

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “translations”: [
      {
      “id”: “item1”,
      “original”: “Hello World”,
      “translated”: “Hola Mundo”
      },
      {
      “id”: “item2”,
      “original”: “Welcome to our site”,
      “translated”: “Bienvenido a nuestro sitio”
      },
      {
      “id”: “item3”,
      “original”: “Contact Us”,
      “translated”: “Contáctenos”
      }
      ],
      “total”: 3,
      “successful”: 3,
      “failed”: 0
      }
      }
      `

      Posts & Pages

      Get Translated Post

      Endpoint: GET /shahitranslate/v1/posts/{post_id}/translations/{language}

      Authentication: None for public posts

      Parameters:

    • post_id (required): Post ID
    • language (required): Language code
    • Response:
      `json
      {
      “success”: true,
      “data”: {
      “id”: 123,
      “title”: “Bienvenido a nuestro blog”,
      “content”: “Este es el contenido traducido…”,
      “excerpt”: “Extracto traducido…”,
      “url”: “https://yoursite.com/es/bienvenido-a-nuestro-blog”,
      “language”: “es”,
      “translation_method”: “manual”,
      “last_updated”: “2024-01-15T10:30:00”
      }
      }
      `

      Create/Update Translation

      Endpoint: POST /shahitranslate/v1/posts/{post_id}/translations

      Authentication: Required (edit_posts capability)

      Parameters:

    • post_id (required): Post ID
    • language (required, string): Target language code
    • title (optional, string): Translated title
    • content (optional, string): Translated content
    • excerpt (optional, string): Translated excerpt
    • status (optional, string): ‘draft’ or ‘published’ (default: ‘published’)
    • Request Body:
      `json
      {
      “language”: “es”,
      “title”: “Mi título traducido”,
      “content”: “

      Contenido traducido completo

      “,
      “excerpt”: “Extracto traducido”,
      “status”: “published”
      }
      `

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “translation_id”: 456,
      “post_id”: 123,
      “language”: “es”,
      “status”: “published”,
      “created”: “2024-01-15T10:30:00”
      },
      “message”: “Translation saved successfully”
      }
      `

      Delete Translation

      Endpoint: DELETE /shahitranslate/v1/posts/{post_id}/translations/{language}

      Authentication: Required (delete_posts capability)

      Response:
      `json
      {
      “success”: true,
      “message”: “Translation deleted successfully”
      }
      `

      List Post Translations

      Endpoint: GET /shahitranslate/v1/posts/{post_id}/translations

      Authentication: None for public posts

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “post_id”: 123,
      “available_languages”: [“es”, “fr”, “de”],
      “translations”: {
      “es”: {
      “title”: “Título en español”,
      “status”: “published”,
      “method”: “manual”,
      “url”: “https://yoursite.com/es/titulo-en-espanol”
      },
      “fr”: {
      “title”: “Titre en français”,
      “status”: “published”,
      “method”: “automatic”,
      “url”: “https://yoursite.com/fr/titre-en-francais”
      }
      }
      }
      }
      `

      Cache Management

      Clear Cache

      Endpoint: DELETE /shahitranslate/v1/cache

      Authentication: Required (manage_options capability)

      Parameters (all optional):

    • language (string): Specific language code
    • post_id (int): Specific post ID
    • post_type (string): Specific post type
    • Request:
      `json
      {
      “language”: “es”,
      “post_type”: “post”
      }
      `

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “cleared_items”: 234,
      “freed_space”: “12.5 MB”
      },
      “message”: “Cache cleared successfully”
      }
      `

      Get Cache Statistics

      Endpoint: GET /shahitranslate/v1/cache/stats

      Authentication: Required (manage_options capability)

      Parameters (optional):

    • language (string): Filter by language
    • Response:
      `json
      {
      “success”: true,
      “data”: {
      “total_items”: 1234,
      “total_size”: “45.2 MB”,
      “hit_rate”: 94.5,
      “miss_rate”: 5.5,
      “by_language”: {
      “es”: {
      “items”: 456,
      “size”: “18.1 MB”
      },
      “fr”: {
      “items”: 389,
      “size”: “15.3 MB”
      }
      }
      }
      }
      `

      Statistics

      Get Translation Statistics

      Endpoint: GET /shahitranslate/v1/stats

      Authentication: Required (manage_options capability)

      Parameters (optional):

    • period (string): ‘today’, ‘week’, ‘month’, ‘year’, ‘all’
    • language (string): Filter by language
    • Response:
      `json
      {
      “success”: true,
      “data”: {
      “period”: “month”,
      “total_translations”: 1234,
      “manual_translations”: 234,
      “automatic_translations”: 1000,
      “characters_translated”: 567890,
      “api_calls”: 456,
      “estimated_cost”: 11.36,
      “by_language”: {
      “es”: {
      “translations”: 567,
      “characters”: 234567
      },
      “fr”: {
      “translations”: 456,
      “characters”: 198765
      }
      },
      “byposttype”: {
      “post”: 789,
      “page”: 234,
      “product”: 211
      }
      }
      }
      `

      Error Responses

      Error Format

      `json
      {
      “success”: false,
      “code”: “error_code”,
      “message”: “Human-readable error message”,
      “data”: {
      “status”: 400
      }
      }
      `

      Common Error Codes

      | Code | Status | Description |
      |——|——–|————-|
      | rest_forbidden | 401 | Authentication required |
      | restforbiddencontext | 403 | Insufficient permissions |
      | restinvalidparam | 400 | Invalid parameter |
      | restmissingcallback_param | 400 | Required parameter missing |
      | stptranslationfailed | 500 | Translation process failed |
      | stpapierror | 502 | Google Translate API error |
      | stplanguagenot_active | 400 | Requested language not active |
      | stppostnot_found | 404 | Post not found |

      Rate Limiting

      Default Limits

    • Authenticated users: 100 requests per minute
    • Unauthenticated: 20 requests per minute
    • Batch operations: 10 requests per minute
    • Rate Limit Headers

      Response includes headers:
      `
      X-RateLimit-Limit: 100
      X-RateLimit-Remaining: 95
      X-RateLimit-Reset: 1640000000
      `

      Exceeding Limits

      Response (HTTP 429):
      `json
      {
      “success”: false,
      “code”: “restratelimit_exceeded”,
      “message”: “Rate limit exceeded. Try again in 60 seconds.”,
      “data”: {
      “status”: 429,
      “retry_after”: 60
      }
      }
      `

      Webhooks

      Registering Webhooks

      Endpoint: POST /shahitranslate/v1/webhooks

      Authentication: Required (manage_options capability)

      Request:
      `json
      {
      “url”: “https://yourapp.com/webhook”,
      “events”: [“translation.created”, “translation.updated”, “cache.cleared”],
      “secret”: “yourwebhooksecret”
      }
      `

      Response:
      `json
      {
      “success”: true,
      “data”: {
      “webhook_id”: 123,
      “url”: “https://yourapp.com/webhook”,
      “events”: [“translation.created”, “translation.updated”, “cache.cleared”],
      “status”: “active”
      }
      }
      `

      Available Events

    • translation.created: New translation created
    • translation.updated: Translation modified
    • translation.deleted: Translation removed
    • language.activated: Language enabled
    • language.deactivated: Language disabled
    • cache.cleared: Cache cleared
    • settings.updated: Plugin settings changed
    • Webhook Payload

      `json
      {
      “event”: “translation.created”,
      “timestamp”: “2024-01-15T10:30:00Z”,
      “data”: {
      “post_id”: 123,
      “language”: “es”,
      “translation_id”: 456,
      “method”: “manual”
      },
      “signature”: “sha256=abcdef…”
      }
      `

      Verifying Webhook Signature

      `php
      $payload = filegetcontents(‘php://input’);
      $signature = $SERVER[‘HTTPXSHAHITRANSLATESIGNATURE’];
      $expected = ‘sha256=’ . hashhmac(‘sha256’, $payload, $webhooksecret);

      if (hash_equals($expected, $signature)) {
      // Signature valid, process webhook
      $data = json_decode($payload, true);
      }
      `

      SDK Examples

      JavaScript/Node.js SDK

      `javascript
      class ShahiTranslateAPI {
      constructor(baseUrl, username, password) {
      this.baseUrl = baseUrl;
      this.auth = ‘Basic ‘ + btoa(${username}:${password});
      }

      async translate(content, language, options = {}) {
      const response = await fetch(${this.baseUrl}/shahitranslate/v1/translate, {
      method: ‘POST’,
      headers: {
      ‘Content-Type’: ‘application/json’,
      ‘Authorization’: this.auth
      },
      body: JSON.stringify({
      content,
      language,
      …options
      })
      });

      return await response.json();
      }

      async getLanguages() {
      const response = await fetch(${this.baseUrl}/shahitranslate/v1/languages);
      return await response.json();
      }

      async getPostTranslation(postId, language) {
      const response = await fetch(
      ${this.baseUrl}/shahitranslate/v1/posts/${postId}/translations/${language}
      );
      return await response.json();
      }
      }

      // Usage
      const api = new ShahiTranslateAPI(
      ‘https://yoursite.com/wp-json’,
      ‘username’,
      ‘app_password’
      );

      const result = await api.translate(‘Hello World’, ‘es’);
      console.log(result.data.translated);
      `

      Python SDK

      `python
      import requests
      from requests.auth import HTTPBasicAuth

      class ShahiTranslateAPI:
      def init(self, base_url, username, password):
      self.baseurl = baseurl
      self.auth = HTTPBasicAuth(username, password)

      def translate(self, content, language, **options):
      response = requests.post(
      f'{self.base_url}/shahitranslate/v1/translate’,
      auth=self.auth,
      json={
      ‘content’: content,
      ‘language’: language,
      **options
      }
      )
      return response.json()

      def get_languages(self):
      response = requests.get(
      f'{self.base_url}/shahitranslate/v1/languages’
      )
      return response.json()

      def getposttranslation(self, post_id, language):
      response = requests.get(
      f'{self.baseurl}/shahitranslate/v1/posts/{postid}/translations/{language}’
      )
      return response.json()

      Usage

      api = ShahiTranslateAPI(
      ‘https://yoursite.com/wp-json’,
      ‘username’,
      ‘app_password’
      )

      result = api.translate(‘Hello World’, ‘es’)
      print(result[‘data’][‘translated’])
      `

      Best Practices

      1. Use Batch Endpoints

      Instead of multiple single requests:
      `javascript
      // ❌ Bad: Multiple requests
      for (let text of texts) {
      await api.translate(text, ‘es’);
      }

      // ✅ Good: Single batch request
      await api.batchTranslate(texts.map((text, i) => ({
      id: i,
      content: text
      })), ‘es’);
      `

      2. Cache Results

      `javascript
      const cache = new Map();

      async function translate(content, language) {
      const cacheKey = ${content}_${language};

      if (cache.has(cacheKey)) {
      return cache.get(cacheKey);
      }

      const result = await api.translate(content, language);
      cache.set(cacheKey, result);

      return result;
      }
      `

      3. Handle Rate Limits

      `javascript
      async function translateWithRetry(content, language, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) { try { return await api.translate(content, language); } catch (error) { if (error.code === 'restratelimit_exceeded’ && i < maxRetries - 1) { const retryAfter = error.data.retry_after || 60; await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      continue;
      }
      throw error;
      }
      }
      }
      `

      4. Validate Responses

      `javascript
      function isValidResponse(response) {
      return response &&
      response.success === true &&
      response.data &&
      typeof response.data === ‘object’;
      }

      const result = await api.translate(‘Hello’, ‘es’);
      if (isValidResponse(result)) {
      console.log(result.data.translated);
      } else {
      console.error(‘Invalid response:’, result);
      }
      `

      Next Steps

    • WP-CLI Commands
    • Hooks and Filters
    • Template Functions
    • Performance Optimization

Share this article

Was this article helpful?

Help us improve our documentation

Still need help?

Our support team is ready to assist you with personalized guidance for your workspace.

Submit a support ticket