בקשה ואחזור של תרגומים דרך ה־API
השתמשו ב־API זה כדי לשלוח תוכן לתרגום, לעקוב אחר ההתקדמות שלו, ולאחזר את התרגומים בכל שפות היעד.
ה־API הזה מקבל תוכן מובנה ב־JSON, ושומר על המבנה והמפתחות המקוריים. הוא מתרגם רק ערכי טקסט, ומשאיר מספרים, ערכים בוליאניים, ערכי null וערכים אחרים שאינם טקסט ללא שינוי.
קישורים מהירים ל־API
Create Content Translations
יוצר משימת תרגום חדשה מנתונים מובנים ב־JSON.
ה־endpoint שומר על ההיררכיה המקורית של המפתחות והמערכים בתוכן שלכם, ומתרגם רק ערכי טקסט בעודו משאיר מספרים, ערכים בוליאניים, ערכי null וערכים אחרים שאינם טקסט ללא שינוי.
הוא שימושי במיוחד עבור:
- ניהול תוכן – לוקליזציה של תוכן דינמי מובנה ב־JSON
- קובצי תצורה – תרגום מחרוזות ממשק בנתוני תצורה
- תשובות API – תרגום נתונים מובנים בתשובות
- תיעוד – לוקליזציה של תוכן עזרה היררכי או מדריכים
ליישום מלא של תהליך זה ב־Rails, ראו תרגום תוכן דינמי ב־Rails באמצעות ה־API של PTC.
בקשת HTTP
POST https://app.ptc.wpml.org/api/v1/content_translationפרמטרים
| פרמטר | סוג | חובה | תיאור |
|---|---|---|---|
data |
אובייקט | כן | הנתונים המובנים ב־JSON לתרגום. הם יכולים לכלול אובייקטים מקוננים, מערכים וערכי מחרוזות. |
name |
מחרוזת | לא | שם קריא לאדם עבור משימת התרגום. אם יושמט, ייווצר שם באופן אוטומטי. |
callback_url |
מחרוזת | לא | כתובת ה־URL שמקבלת התראות webhook כאשר התרגום מסתיים. |
target_languages |
מערך[מחרוזת] | לא | מערך קודי ה־ISO של שפות היעד. אם יושמט, ייווצרו תרגומים לכל השפות המוגדרות בפרויקט. למידע נוסף, ראו API שפות יעד זמינות. |
דוגמה לגוף הבקשה
{
"data": {
"app": {
"title": "My Application",
"navigation": {
"home": "Home",
"about": "About Us",
"contact": "Contact"
},
"buttons": {
"save": "Save",
"cancel": "Cancel",
"submit": "Submit"
},
"messages": {
"welcome": "Welcome to our platform",
"error": "An error occurred"
}
},
"version": "1.0.0",
"settings": {
"theme": "dark",
"notifications": true
}
},
"name": "App UI Translations",
"callback_url": "https://your-app.com/webhooks/translation-complete",
"target_languages": ["es", "fr", "de"]
}תשובות
תשובת הצלחה
{
"id": 123,
"name": "App UI Translations",
"status": "queued",
"created_at": "2024-01-15T10:30:00.000Z",
"updated_at": "2024-01-15T10:30:00.000Z"
}סכמת התשובה
| שדה | סוג | תיאור |
|---|---|---|
id |
מספר | המזהה הייחודי של משימת תרגום התוכן. |
name |
מחרוזת | שם המשימה (נוצר אוטומטית אם לא סופק). |
status |
מחרוזת | הסטטוס הנוכחי של המשימה (queued, processing, completed). |
created_at |
מחרוזת | חותמת הזמן בפורמט ISO 8601 המציינת מתי המשימה נוצרה. |
updated_at |
מחרוזת | חותמת הזמן בפורמט ISO 8601 המציינת מתי המשימה עודכנה לאחרונה. |
תשובות שגיאה
נתוני JSON לא תקינים
{
"errors": {
"data": ["Data must be a valid JSON object"]
}
}שפות יעד לא תקינות
{
"errors": {
"target_languages": ["Language codes [zh, xx] are not configured for this project"]
}
}לא מורשה
{
"error": "Unauthorized access. Please provide a valid API token."
}גישה נדחתה
{
"error": "Access denied. Insufficient permissions."
}עיבוד נתוני JSON
בעבודה עם נתונים מובנים ב־JSON, PTC מעבדת את הנתונים באופן הבא:
- המבנה נשמר – ההיררכיה המקורית של המפתחות והקינון נשארת ללא שינוי
- רק מחרוזות מתורגמות – מספרים, ערכים בוליאניים, מערכים וערכי null נשמרים כפי שהם
- תרגום מבוסס נתיב – כל מחרוזת הניתנת לתרגום מזוהה על ידי נתיב ה־JSON שלה
- תמיכה בקינון – עובד עם אובייקטים ומערכים מקוננים עמוקות
- תמיכה בסוגי נתונים מעורבים – ערכים שאינם מחרוזות נשמרים ללא שינוי
דוגמה להמרת נתונים
קלט:
{
"user": {
"name": "Welcome User",
"settings": {
"theme": "Choose Theme",
"count": 5,
"enabled": true
}
}
}תוצאת העיבוד:
user.name: “Welcome User” ← מתורגםuser.settings.theme: “Choose Theme” ← מתורגםuser.settings.count:5 ← נשאר ללא שינויuser.settings.enabled:true ← נשאר ללא שינוי
תהליך התרגום
- אימות: מבנה ה־JSON ושפות היעד נבדקים
- הכנת קובץ המקור: ה־JSON מומר לפורמט מקור פנימי
- שימוש חוזר במחרוזות דרך זיכרון תרגומי: כל המחרוזות הניתנות לתרגום מחולצות ונשמרות בזיכרון התרגומי של הפרויקט שלכם, כך שניתן יהיה לעשות שימוש חוזר בתרגומים קודמים
- הכנסת משימות לתור: משימה נכנסת לתור עבור כל שפת יעד
- עיבוד: תרגום אוטומטי רץ על המחרוזות שחולצו
- Callback (אופציונלי): נשלח webhook כאשר כל התרגומים מסתיימים, אם סופק
callback_url
Webhook Callback
כאשר מסופק callback_url, נשלחת בקשת POST עם סיום המשימה.
גוף בקשת ה־callback:
{
"id": 1,
"status": "completed",
"translations_url": "https://app.ptc.wpml.org/api/v1/content_translation/1"
}סוגי נתונים נתמכים
| סוג JSON | התנהגות תרגום |
|---|---|
string |
מתורגם לשפות היעד |
number |
נשמר כפי שהוא |
boolean |
נשמר כפי שהוא |
null |
נשמר כפי שהוא |
array |
מעובד באופן רקורסיבי |
object |
מעובד באופן רקורסיבי |
דוגמאות לבקשות
תרגום JSON בסיסי:
curl -X POST "https://app.ptc.wpml.org/api/v1/content_translation" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"data": {
"welcome": "Welcome",
"buttons": {
"save": "Save",
"cancel": "Cancel"
}
},
"name": "UI Labels"
}'עם שפות יעד ספציפיות:
curl -X POST "https://app.ptc.wpml.org/api/v1/content_translation" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"data": {
"title": "Product Catalog",
"categories": {
"electronics": "Electronics",
"clothing": "Clothing"
}
},
"target_languages": ["es", "fr"],
"callback_url": "https://myapp.com/webhook"
}'דוגמאות קוד
curl -X POST "https://app.ptc.wpml.org/api/v1/content_translation" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"data":{"app":{"title":"My Application","navigation":{"home":"Home","about":"About Us"}}},"name":"App Translations","target_languages":["es","fr","de"],"callback_url":"https://your-app.com/webhooks/complete"}'
# The response includes the job "id". Poll its status (status stays
# "in_progress" until done — it is not set on the create response):
curl -X GET "https://app.ptc.wpml.org/api/v1/content_translation/CONTENT_TRANSLATION_ID/status" \
-H "Authorization: Bearer YOUR_API_TOKEN"require 'net/http'
require 'uri'
require 'json'
uri = URI('https://app.ptc.wpml.org/api/v1/content_translation')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer YOUR_API_TOKEN'
request['Content-Type'] = 'application/json'
request.body = {
data: { app: { title: 'My Application',
navigation: { home: 'Home', about: 'About Us' } } },
name: 'App Translations',
target_languages: %w[es fr de],
callback_url: 'https://your-app.com/webhooks/complete'
}.to_json
response = http.request(request)
id = JSON.parse(response.body)['id']
puts "Translation job created with ID: #{id}"
# Poll the status endpoint for progress (status is set there, not on create)
status_uri = URI("https://app.ptc.wpml.org/api/v1/content_translation/#{id}/status")
status_request = Net::HTTP::Get.new(status_uri)
status_request['Authorization'] = 'Bearer YOUR_API_TOKEN'
status = JSON.parse(http.request(status_request).body)
puts "Status: #{status['status']} (#{status['completeness']}% complete)"import requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN',
'Content-Type': 'application/json'
}
payload = {
"data": {"app": {"title": "My Application",
"navigation": {"home": "Home", "about": "About Us"}}},
"name": "App Translations",
"target_languages": ["es", "fr", "de"],
"callback_url": "https://your-app.com/webhooks/complete"
}
response = requests.post('https://app.ptc.wpml.org/api/v1/content_translation', headers=headers, json=payload)
translation_id = response.json()['id']
print(f"Translation job created with ID: {translation_id}")
# Poll the status endpoint for progress (status is set there, not on create)
status_response = requests.get(f'https://app.ptc.wpml.org/api/v1/content_translation/{translation_id}/status', headers=headers)
status = status_response.json()
print(f"Status: {status['status']} ({status['completeness']}% complete)")<?php
$payload = [
'data' => ['app' => ['title' => 'My Application',
'navigation' => ['home' => 'Home', 'about' => 'About Us']]],
'name' => 'App Translations',
'target_languages' => ['es', 'fr', 'de'],
'callback_url' => 'https://your-app.com/webhooks/complete'
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://app.ptc.wpml.org/api/v1/content_translation',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN',
'Content-Type: application/json'
],
]);
$response = curl_exec($curl);
curl_close($curl);
$id = json_decode($response, true)['id'];
echo "Translation job created with ID: " . $id . "\n";
// Poll the status endpoint for progress (status is set there, not on create)
$statusCurl = curl_init();
curl_setopt_array($statusCurl, [
CURLOPT_URL => "https://app.ptc.wpml.org/api/v1/content_translation/{$id}/status",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_TOKEN'],
]);
$status = json_decode(curl_exec($statusCurl), true);
curl_close($statusCurl);
echo "Status: " . $status['status'] . " (" . $status['completeness'] . "% complete)";
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json");
String payload = "{"
+ "\"data\":{\"app\":{\"title\":\"My Application\",\"navigation\":{\"home\":\"Home\",\"about\":\"About Us\"}}},"
+ "\"name\":\"App Translations\",\"target_languages\":[\"es\",\"fr\",\"de\"],"
+ "\"callback_url\":\"https://your-app.com/webhooks/complete\"}";
Request request = new Request.Builder()
.url("https://app.ptc.wpml.org/api/v1/content_translation")
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.post(RequestBody.create(payload, JSON))
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());package main
import (
"bytes"
"fmt"
"io"
"net/http"
)
func main() {
payload := []byte(`{
"data": {"app": {"title": "My Application",
"navigation": {"home": "Home", "about": "About Us"}}},
"name": "App Translations",
"target_languages": ["es", "fr", "de"],
"callback_url": "https://your-app.com/webhooks/complete"
}`)
req, _ := http.NewRequest("POST", "https://app.ptc.wpml.org/api/v1/content_translation", bytes.NewBuffer(payload))
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
req.Header.Add("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_TOKEN");
var payload = @"{
""data"": {""app"": {""title"": ""My Application"",
""navigation"": {""home"": ""Home"", ""about"": ""About Us""}}},
""name"": ""App Translations"",
""target_languages"": [""es"", ""fr"", ""de""],
""callback_url"": ""https://your-app.com/webhooks/complete""
}";
var body = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://app.ptc.wpml.org/api/v1/content_translation", body);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);const axios = require('axios');
const payload = {
data: {
app: {
title: "My Application",
navigation: { home: "Home", about: "About Us" }
}
},
name: "App Translations",
target_languages: ["es", "fr", "de"],
callback_url: "https://your-app.com/webhooks/complete"
};
const response = await axios.post('https://app.ptc.wpml.org/api/v1/content_translation', payload, {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' }
});
const translationId = response.data.id;
console.log('Translation job created with ID:', translationId);
// Poll the status endpoint for progress (status is set there, not on create)
const status = await axios.get(`https://app.ptc.wpml.org/api/v1/content_translation/${translationId}/status`, {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' }
});
console.log(`Status: ${status.data.status} (${status.data.completeness}% complete)`);Get Content Translations
מאחזר את התוכן המקורי ואת כל הגרסאות המתורגמות עבור משימת תרגום תוכן ספציפית.
התשובה שומרת על מבנה הקלט שלכם: היא מחזירה אובייקט מקור בתוספת אובייקט אחד לכל שפת יעד (מזוהה על ידי קוד השפה, כגון es, fr, de).
בקשת HTTP
GET https://app.ptc.wpml.org/api/v1/content_translation/{id}פרמטרי נתיב
| פרמטר | סוג | חובה | תיאור |
|---|---|---|---|
id |
מספר שלם | כן | המזהה הייחודי של משימת תרגום התוכן שיש לאחזר. |
תשובות
תשובת הצלחה
{
"source": {
"app": {
"title": "My Application",
"navigation": {
"home": "Home",
"about": "About",
"contact": "Contact"
},
"buttons": {
"save": "Save",
"cancel": "Cancel"
}
}
},
"es": {
"app": {
"title": "Mi Aplicación",
"navigation": {
"home": "Inicio",
"about": "Acerca de",
"contact": "Contacto"
},
"buttons": {
"save": "Guardar",
"cancel": "Cancelar"
}
}
},
"fr": {
"app": {
"title": "Mon Application",
"navigation": {
"home": "Accueil",
"about": "À propos",
"contact": "Contact"
},
"buttons": {
"save": "Enregistrer",
"cancel": "Annuler"
}
}
}
}סכמת התשובה
| שדה | סוג | תיאור |
|---|---|---|
source |
אובייקט | תוכן המקור המקורי באותו מבנה מקונן כפי שהוגש. |
{language_code} |
אובייקט | התוכן המתורגם עבור כל שפת יעד, מזוהה על ידי קוד ה־ISO שלה (לדוגמה es, fr, de), באותו מבנה כמו המקור. למידע נוסף, ראו API שפות יעד זמינות. |
תשובות שגיאה
תרגום התוכן לא נמצא
{
"error": "Content translation not found"
}לא מורשה
{
"error": "Unauthorized access. Please provide a valid API token."
}גישה נדחתה
{
"error": "Access denied. Insufficient permissions."
}דוגמאות לבקשות
בקשה בסיסית:
curl -X GET "https://app.ptc.wpml.org/api/v1/content_translation/123" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"דוגמאות קוד
curl -X GET "https://app.ptc.wpml.org/api/v1/content_translation/123" \
-H "Authorization: Bearer YOUR_API_TOKEN"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/content_translation/123')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer YOUR_API_TOKEN'
response = http.request(request)
require 'json'
data = JSON.parse(response.body)
puts "Source: #{data['source']}"
data.each { |lang, translation| puts "#{lang}: #{translation}" unless lang == 'source' }import requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
response = requests.get('https://app.ptc.wpml.org/api/v1/content_translation/123', headers=headers)
data = response.json()
print('Source:', data['source'])
for lang_code, translation in data.items():
if lang_code != 'source':
print(f"{lang_code}:", translation)<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://app.ptc.wpml.org/api/v1/content_translation/123',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
foreach ($data as $langCode => $translation) {
echo strtoupper($langCode) . ": " . json_encode($translation) . "\n";
}
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://app.ptc.wpml.org/api/v1/content_translation/123")
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());package main
import (
"fmt"
"io"
"net/http"
)
func main() {
req, _ := http.NewRequest("GET", "https://app.ptc.wpml.org/api/v1/content_translation/123", nil)
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_TOKEN");
var response = await client.GetAsync("https://app.ptc.wpml.org/api/v1/content_translation/123");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);const axios = require('axios');
const response = await axios.get('https://app.ptc.wpml.org/api/v1/content_translation/123', {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' }
});
const data = response.data;
console.log('Source:', data.source);
Object.keys(data).forEach(lang => {
if (lang !== 'source') console.log(`${lang}:`, data[lang]);
});Get the Content Translation Status
מאחזר את הסטטוס הנוכחי של משימת תרגום תוכן ספציפית.
התשובה משקפת את ההתקדמות הכללית וכוללת האם התרגום נמצא בתור, בתהליך, הושלם או נכשל.
בקשת HTTP
GET https://app.ptc.wpml.org/api/v1/content_translation/{id}/statusפרמטרי נתיב
| פרמטר | סוג | חובה | תיאור |
|---|---|---|---|
id |
מספר שלם | כן | המזהה הייחודי של משימת תרגום התוכן לבדיקה. |
תשובות
תשובת הצלחה
{
"status": "completed",
"completeness": 100
}סכמת התשובה
| שדה | סוג | תיאור |
|---|---|---|
status |
מחרוזת | סטטוס התרגום הנוכחי. ערכי הסטטוס האפשריים כוללים: queued, in_progress, completed, failed, status_unknown. |
completeness |
מספר | אחוז ההשלמה של המחרוזות שתורגמו (0–100). מחושב כ־(completed_translatable_strings / total_translatable_strings) × 100. |
ערכי סטטוס
| סטטוס | תיאור |
|---|---|
queued |
התרגום הוכנס לתור וממתין לעיבוד. |
in_progress |
התרגום נמצא כעת בעיבוד. |
completed |
התרגום הושלם בהצלחה. |
failed |
התרגום נכשל עקב שגיאה. |
status_unknown |
סטטוס התרגום אינו ידוע או שעדיין לא ניתן לקבוע אותו. |
תשובות שגיאה
סיבות אפשריות:
- לא קיים תרגום תוכן עם המזהה שצוין
- משימת התרגום אינה שייכת לפרויקט המאומת
דוגמה
curl -X GET "https://app.ptc.wpml.org/api/v1/content_translation/123/status" \
-H "Authorization: Bearer YOUR_API_TOKEN"תשובה:
{
"status": "completed",
"completeness": 100
}תשובה בזמן שהמשימה עדיין רצה:
{
"status": "in_progress",
"completeness": 70
}{
"status": "completed",
"completeness": 100
}