Carica e gestisci i file di origine tramite l'API
Usa questa API per caricare nuovi file di origine, sostituire quelli obsoleti, monitorare l'avanzamento della traduzione e scaricare le traduzioni completate.
Che tu stia gestendo un singolo file o automatizzando un flusso di lavoro di localizzazione continua, questa API ti offre il pieno controllo sui contenuti che invii per la traduzione e su come ricevi le traduzioni.
Link rapidi dell'API
Come l'API PTC identifica e organizza i file di origine
L'API PTC utilizza un sistema flessibile basato sui tag del file e sui percorsi dei file. Questi parametri lavorano insieme per garantire che ogni file caricato, aggiornato o richiesto sia chiaramente definito e facile da gestire.
Tag del file
I tag del file sono un modo flessibile per raggruppare e organizzare i file di origine nei progetti di traduzione. Puoi usarli come categorie per soddisfare le esigenze del tuo flusso di lavoro. Ad esempio, i tag del file possono indicare:
- Controllo della versione:
v1.0,beta,production - Branch di funzionalità:
user-auth,dashboard-redesign - Contesto dell'applicazione:
mobile-app,admin-panel,marketing - Proprietà del team:
frontend-team,content-team - Stato del flusso di lavoro:
approved,pending-review,priority-high
I nomi dei tag del file sono facoltativi nella maggior parte delle operazioni dell'API. Tuttavia, ogni file di origine ha sempre almeno un tag. Un tag del file predefinito viene creato e assegnato automaticamente quando si configura un progetto. Questo comportamento predefinito mantiene i progetti organizzati anche in configurazioni semplici, consentendoti al contempo di creare strutture di tag più avanzate quando necessario.
Nome del tag del file + Percorso del file
Ogni file di origine è identificato in modo univoco dalla combinazione del suo nome del tag del file e del percorso del file.
- Se non fornisci un tag del file personalizzato durante il caricamento o l'elaborazione di un file, verrà assegnato automaticamente il tag predefinito.
- Il nome del tag + il percorso di un file ne definiscono insieme l'identità. Questa combinazione assicura che ogni file sia unico all'interno del tuo progetto, anche se versioni o contesti diversi condividono lo stesso percorso del file.
Parametri di query
Quando si recupera un file specifico, i relativi endpoint possono accettare parametri di query come:
file_tag_name– Il tag associato al filefile_path– Il percorso del file
Questi parametri ti consentono di individuare con precisione e recuperare i file corretti dal tuo progetto.
Elenca tutti i file di origine nel progetto
Elenca tutti i file di origine nel tuo progetto, con opzioni per filtrare, ordinare e impaginare i risultati. Questo è utile quando desideri sfogliare i tuoi file, controllarne lo stato o trovare file specifici in base al tag, al percorso o al metodo di caricamento.
Richiesta HTTP
GET https://app.ptc.wpml.org/api/v1/source_filesParametri
| Parametro | Tipo | Obbligatorio | Predefinito | Descrizione |
|---|---|---|---|---|
page |
integer | No | 1 |
Il numero di pagina per l'impaginazione. Deve essere maggiore di 0. |
per_page |
integer | No | 50 |
Il numero di elementi per pagina. Deve essere maggiore di 0. |
order_by |
string | No | created_at |
Il campo in base al quale ordinare. Valori consentiti: id, created_at, updated_at. |
sort |
string | No | desc |
La direzione dell'ordinamento. Valori consentiti: asc, desc. |
file_path |
string | No | – | Filtra in base all'esatto percorso del file. |
upload_origin |
string | No | – | Filtra in base alla modalità di caricamento del file. I valori consentiti includono: git, manual, api. |
Risposte
Risposta di successo
{
"source_files": [
{
"id": 123,
"file_path": "locales/en.po",
"translation_path": "locales/{{lang}}.po",
"additional_translation_files": ["locales/{{lang}}.mo"],
"status": "completed",
"upload_origin": "git",
"created_at": "2024-01-15T10:30:00.000Z",
"updated_at": "2024-01-15T14:20:00.000Z",
"file_tag": {
"id": 456,
"name": "frontend"
},
"download_url": "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=locales/en.po&file_tag_name=frontend"
}
],
"pagination": {
"page": 1,
"per_page": 50,
"total": 150,
"total_pages": 3,
"has_next_page": true,
"has_previous_page": false
}
}Schema della risposta
Oggetto file di origine:
| Campo | Tipo | Descrizione |
|---|---|---|
id |
integer | L'identificatore univoco del file di origine. |
file_path |
string | Il percorso del file di origine all'interno del progetto. |
translation_path |
string | Il modello che indica dove devono essere salvati i file tradotti. |
additional_translation_files |
array[string] | I percorsi per eventuali file di output aggiuntivi. |
status |
string | L'attuale stato di elaborazione del file di origine. |
upload_origin |
string | La modalità di caricamento del file (git, manual, api). |
created_at |
string | Un timestamp ISO 8601 che indica quando il file di origine è stato creato originariamente. |
updated_at |
string | Un timestamp ISO 8601 che indica quando il file di origine è stato aggiornato l'ultima volta. |
file_tag |
object | Informazioni sul tag del file. |
file_tag.id |
integer | L'identificatore del tag del file. |
file_tag.name |
string | Il nome del tag del file. |
download_url |
string | L'URL per scaricare le traduzioni per questo file di origine. |
Oggetto impaginazione:
| Campo | Tipo | Descrizione |
|---|---|---|
page |
integer | Il numero di pagina corrente. |
per_page |
integer | Il numero di elementi per pagina. |
total |
integer | Il numero totale di file di origine. |
total_pages |
integer | Il numero totale di pagine. |
has_next_page |
boolean | Indica se è disponibile una pagina successiva. |
has_previous_page |
boolean | Indica se è disponibile una pagina precedente. |
Risposte di errore
Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Parametri non validi
{
"error": "Invalid parameters provided."
}Richieste di esempio
Richiesta di base:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Richiesta filtrata:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files?file_tag_name=frontend&page=1&per_page=25&order_by=updated_at&sort=desc" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Esempi di codice
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files?file_tag_name=frontend&page=1&per_page=25" \
-H "Authorization: Bearer YOUR_API_TOKEN"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files')
uri.query = URI.encode_www_form(file_tag_name: 'frontend', page: 1, per_page: 25)
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)
puts response.bodyimport requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
params = {
'file_tag_name': 'frontend',
'page': 1,
'per_page': 25
}
response = requests.get('https://app.ptc.wpml.org/api/v1/source_files',
headers=headers, params=params)
print(response.json())<?php
$params = http_build_query([
'file_tag_name' => 'frontend',
'page' => 1,
'per_page' => 25
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://app.ptc.wpml.org/api/v1/source_files?{$params}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r(json_decode($response, true));
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
HttpUrl url = HttpUrl.parse("https://app.ptc.wpml.org/api/v1/source_files")
.newBuilder()
.addQueryParameter("file_tag_name", "frontend")
.addQueryParameter("page", "1")
.addQueryParameter("per_page", "25")
.build();
Request request = new Request.Builder()
.url(url)
.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/source_files", nil)
q := req.URL.Query()
q.Add("file_tag_name", "frontend")
q.Add("page", "1")
q.Add("per_page", "25")
req.URL.RawQuery = q.Encode()
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/source_files?file_tag_name=frontend&page=1&per_page=25");
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/source_files', {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' },
params: {
file_tag_name: 'frontend',
page: 1,
per_page: 25
}
});
console.log(response.data);Ottieni le stringhe di traduzione
Recupera tutte le stringhe traducibili da un file di origine specifico, insieme alle rispettive traduzioni esistenti in tutte le lingue di destinazione.
Questo endpoint è utile per recuperare contenuti che devono essere tradotti o che sono già stati tradotti. Il file di origine è identificato da file_path e file_tag_name.
Richiesta HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_stringsParametri
| Parametro | Tipo | Obbligatorio | Predefinito | Descrizione |
|---|---|---|---|---|
file_path |
string | Sì | – | Il percorso del file di origine all'interno del progetto. |
file_tag_name |
string | No | – | Il nome del tag del file. Se non fornito, viene utilizzato il tag predefinito del progetto. |
page |
integer | No | 1 |
Il numero di pagina per l'impaginazione (utilizzato come cursore). Deve essere maggiore di 0. |
q |
string | No | – | La query di ricerca per filtrare le stringhe di traduzione in base al loro testo di origine. |
Risposte
Risposta di successo
{
"total_strings_count": 1250,
"translation_strings": [
{
"source": "Welcome to our application",
"translations": {
"es": "Bienvenido a nuestra aplicación",
"fr": "Bienvenue dans notre application",
"de": "Willkommen in unserer Anwendung"
}
},
{
"source": "Login",
"translations": {
"es": "Iniciar sesión",
"fr": "Connexion",
"de": "Anmelden"
}
}
],
"cursor": 1
}Schema della risposta
| Campo | Tipo | Descrizione |
|---|---|---|
total_strings_count |
integer | Il numero totale di stringhe traducibili nel file di origine. |
translation_strings |
array[object] | L'array degli oggetti stringa di traduzione (impaginato, massimo 500 per pagina). |
translation_strings[].source |
string | Il testo di origine originale da tradurre. |
translation_strings[].translations |
object | Un hash di traduzioni in cui le chiavi sono i codici ISO della lingua e i valori sono il testo tradotto. |
cursor |
integer | Il cursore della pagina corrente utilizzato per l'impaginazione. |
Risposte di errore
File di origine non trovato
{
"error": "Source file not found"
}Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Parametri non validi
{
"error": "Invalid parameters provided."
}Richieste di esempio
Richiesta di base:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_strings?file_path=locales/en.po" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Una richiesta con tag del file:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_strings?file_path=locales/en.po&file_tag_name=frontend" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Una richiesta con impaginazione e ricerca:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_strings?file_path=locales/en.po&file_tag_name=frontend&page=2&q=welcome" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Esempi di codice
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_strings?file_path=locales/en.po&file_tag_name=frontend&page=1&q=login" \
-H "Authorization: Bearer YOUR_API_TOKEN"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files/translation_strings')
uri.query = URI.encode_www_form(file_path: 'locales/en.po', file_tag_name: 'frontend', page: 1, q: 'login')
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)
puts response.bodyimport requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
params = {
'file_path': 'locales/en.po',
'file_tag_name': 'frontend',
'page': 1,
'q': 'login'
}
response = requests.get('https://app.ptc.wpml.org/api/v1/source_files/translation_strings',
headers=headers, params=params)
print(response.json())<?php
$params = http_build_query([
'file_path' => 'locales/en.po',
'file_tag_name' => 'frontend',
'page' => 1,
'q' => 'login'
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://app.ptc.wpml.org/api/v1/source_files/translation_strings?{$params}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r(json_decode($response, true));
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
HttpUrl url = HttpUrl.parse("https://app.ptc.wpml.org/api/v1/source_files/translation_strings")
.newBuilder()
.addQueryParameter("file_path", "locales/en.po")
.addQueryParameter("file_tag_name", "frontend")
.addQueryParameter("page", "1")
.addQueryParameter("q", "login")
.build();
Request request = new Request.Builder()
.url(url)
.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/source_files/translation_strings", nil)
q := req.URL.Query()
q.Add("file_path", "locales/en.po")
q.Add("file_tag_name", "frontend")
q.Add("page", "1")
q.Add("q", "login")
req.URL.RawQuery = q.Encode()
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/source_files/translation_strings?file_path=locales/en.po&file_tag_name=frontend&page=1&q=login");
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/source_files/translation_strings', {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' },
params: {
file_path: 'locales/en.po',
file_tag_name: 'frontend',
page: 1,
q: 'login'
}
});
console.log(response.data);Crea il file di origine
Registra un nuovo file di origine nel tuo progetto in modo che sia pronto per la traduzione.
Questo endpoint crea la voce del file e ne imposta la configurazione di traduzione, ma non allega il contenuto effettivo del file.
Dopo aver creato il file, dovrai usare l'endpoint Elabora il file di origine per caricare il contenuto e avviare il processo di traduzione.
Richiesta HTTP
POST https://app.ptc.wpml.org/api/v1/source_filesParametri
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
file_path |
string | Sì | Il percorso in cui il file di origine deve essere archiviato nel progetto. Deve avere un'estensione supportata. |
output_file_path |
string | Sì | Il modello di percorso di output per i file tradotti. Usa {{lang}} come segnaposto per il codice della lingua. |
file_tag_name |
string | No | Il nome del tag del file sotto cui registrare il file di origine. Se non fornito, viene utilizzato il tag del file predefinito del progetto. |
translations |
array[object] | No | I file di traduzioni preesistenti da caricare insieme al file di origine. Questi file verranno archiviati così come forniti e le loro stringhe non verranno ritradotte da PTC. Tieni presente che non è consigliato fornire traduzioni esistenti, poiché PTC produce risultati migliori quando può utilizzare l'intero contesto del tuo progetto e tradurre da zero. |
translations[].target_language_iso |
string | Sì | Il codice ISO della lingua di destinazione per questa traduzione. Puoi trovare l'elenco completo delle lingue supportate e i relativi codici ISO nell'endpoint Elenca tutte le lingue di destinazione. |
translations[].file |
file | Sì | Il file di traduzione da caricare. |
additional_translation_files |
array[object] | No | Configurazioni dei file di output aggiuntivi per formati specifici. Per vedere quali formati supportano i file di output aggiuntivi, fai riferimento all'endpoint Elenca i formati di file supportati. Per i formati non supportati, questo campo verrà ignorato. |
additional_translation_files[].type |
string | Sì | Vedi i formati di file supportati per maggiori dettagli. |
additional_translation_files[].path |
string | Sì | Il modello di percorso per il file. |
Risposte
Risposta di successo
{
"source_file": {
"id": 123,
"file_path": "src/locales/en.json",
"created_at": "2024-01-15T10:30:00.000Z",
"file_tag": {
"id": 456,
"name": "frontend"
}
}
}Schema della risposta
| Campo | Tipo | Descrizione |
|---|---|---|
source_file.id |
integer | L'identificatore univoco del file di origine creato. |
source_file.file_path |
string | Il percorso del file di origine all'interno del progetto. |
source_file.created_at |
string | Un timestamp ISO 8601 che indica quando il file di origine è stato creato originariamente. |
source_file.file_tag.id |
integer | L'identificatore del tag del file. |
source_file.file_tag.name |
string | Il nome del tag del file. |
Risposte di errore
Convalida non riuscita
{
"success": false,
"error": "Source file creation failed"
}Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Richieste di esempio
Creazione di base del file di origine:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file_path=src/locales/en.json" \
-F "output_file_path=src/locales/{{lang}}.json" \
-F "file_tag_name=frontend"La creazione non accetta callback_url. La registrazione di un file di origine non avvia alcuna traduzione, quindi non c'è nulla da annunciare per un callback; passalo invece a Elabora il file di origine o a Caricamento in blocco dei file di origine, che sono le chiamate che iniziano il lavoro.
Richiesta con traduzioni preesistenti:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file_path=src/messages.json" \
-F "output_file_path=locales/{{lang}}/messages.json" \
-F "translations[0][target_language_iso]=es" \
-F "translations[0][file]=@spanish_translations.json" \
-F "translations[1][target_language_iso]=fr" \
-F "translations[1][file]=@french_translations.json"Richiesta con file di output aggiuntivi:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file_path=src/messages.po" \
-F "output_file_path=locales/{{lang}}/messages.po" \
-F "additional_translation_files[][type]=mo" \
-F "additional_translation_files[][path]=locales/{{lang}}/messages.mo" \
-F "additional_translation_files[][type]=json" \
-F "additional_translation_files[][path]=locales/{{lang}}/messages.json"Esempi di codice
- JavaScript (FormData)
- Python (requests)
- PHP (cURL)
- Node.js (axios)
- Corpo della richiesta di callback
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file_path=src/locales/en.json" \
-F "output_file_path=src/locales/{{lang}}.json"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files')
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.set_form_data(
'file_path' => 'src/locales/en.json',
'output_file_path' => 'src/locales/{{lang}}.json'
)
response = http.request(request)
puts response.bodyimport requests
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}
data = {
'file_path': 'src/locales/en.json',
'output_file_path': 'src/locales/{{lang}}.json'
}
response = requests.post('https://app.ptc.wpml.org/api/v1/source_files', headers=headers, data=data)
print(response.json())<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://app.ptc.wpml.org/api/v1/source_files',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'file_path' => 'src/locales/en.json',
'output_file_path' => 'src/locales/{{lang}}.json'
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r(json_decode($response, true));
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("file_path", "src/locales/en.json")
.add("output_file_path", "src/locales/{{lang}}.json")
.build();
Request request = new Request.Builder()
.url("https://app.ptc.wpml.org/api/v1/source_files")
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
func main() {
form := url.Values{}
form.Set("file_path", "src/locales/en.json")
form.Set("output_file_path", "src/locales/{{lang}}.json")
req, _ := http.NewRequest("POST", "https://app.ptc.wpml.org/api/v1/source_files", strings.NewReader(form.Encode()))
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
using System;
using System.Collections.Generic;
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 form = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "file_path", "src/locales/en.json" },
{ "output_file_path", "src/locales/{{lang}}.json" }
});
var response = await client.PostAsync("https://app.ptc.wpml.org/api/v1/source_files", form);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);const axios = require('axios');
const params = new URLSearchParams();
params.append('file_path', 'src/locales/en.json');
params.append('output_file_path', 'src/locales/{{lang}}.json');
const response = await axios.post('https://app.ptc.wpml.org/api/v1/source_files', params, {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' }
});
console.log(response.data);{
"source_file_id": 123,
"status": "completed",
"file_tag_name": "frontend",
"download_url": "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=src/locales/en.json&file_tag_name=frontend",
"file_path": "src/locales/en.json"
}Elabora il file di origine
Carica il contenuto in un file di origine esistente e avvia il processo di traduzione.
Questo endpoint sostituisce il contenuto corrente del file, aggiorna le stringhe traducibili archiviate e avvia la traduzione automatica.
Per usare questo endpoint, il file di origine deve già esistere nel progetto. Se non l'hai ancora creato, vedi Crea il file di origine.
Richiesta HTTP
PUT https://app.ptc.wpml.org/api/v1/source_files/processParametri
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
file |
file | Sì | Il file di origine da caricare. Il contenuto del file viene convalidato per garantire che corrisponda all'estensione dichiarata. Ad esempio, se l'estensione del file è .json, il contenuto caricato deve essere un JSON valido. |
file_path |
string | Sì | Il percorso del file di origine esistente nel progetto che deve essere aggiornato. |
file_tag_name |
string | No | Il nome del tag del file associato al file di origine. Se non fornito, viene utilizzato il tag del file predefinito del progetto. |
callback_url |
string | No | L'URL che riceve le notifiche webhook al termine dell'elaborazione del file. |
Risposte
Risposta di successo
{
"source_file": {
"id": 123,
"file_path": "src/locales/en.json",
"created_at": "2024-01-15T10:30:00.000Z",
"file_tag": {
"id": 456,
"name": "frontend"
}
}
}Schema della risposta
| Campo | Tipo | Descrizione |
|---|---|---|
source_file.id |
integer | L'identificatore univoco del file di origine elaborato. |
source_file.file_path |
string | Il percorso del file di origine all'interno del progetto. |
source_file.created_at |
string | Un timestamp ISO 8601 che indica quando il file di origine è stato creato originariamente. |
source_file.file_tag.id |
integer | L'identificatore del tag del file. |
source_file.file_tag.name |
string | Il nome del tag del file. |
Risposte di errore
Formato di file non supportato o non valido
L'elaborazione sostituisce il contenuto del file con quello che carichi, quindi non è possibile che una ricerca fallisca; questo endpoint non ha un caso "non trovato". L'unico rifiuto che restituisce è il controllo del contenuto sul file caricato.
{
"success": false,
"message": "Unprocessable Entity",
"code": 422,
"errors": [9001]
}errors è un array di codici numerici, non un oggetto con chiavi di campo. 9001 significa che il contenuto non è stato analizzato nel formato dichiarato dalla sua estensione. Alcuni rifiuti aggiungono un oggetto additional_info a fianco con le specifiche.
Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Flusso di lavoro
- Prerequisito: Il file di origine deve essere già stato creato tramite Crea il file di origine.
- Caricamento del file: Il nuovo contenuto viene caricato e sostituisce il contenuto del file esistente.
- Elaborazione: Le nuove stringhe traducibili vengono estratte e tradotte automaticamente.
- Callback: Una notifica webhook facoltativa viene inviata al termine dell'elaborazione.
Callback webhook
Quando viene fornito un callback_url, PTC invierà una richiesta POST a quell'URL al termine dell'elaborazione.
Corpo della richiesta di callback:
{
"source_file_id": 123,
"status": "completed",
"file_tag_name": "frontend",
"download_url": "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=src/locales/en.json&file_tag_name=frontend",
"file_path": "src/locales/en.json"
}Richieste di esempio
Elaborazione di base del file:
curl -X PUT "https://app.ptc.wpml.org/api/v1/source_files/process" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file=@updated_translations.json" \
-F "file_path=src/locales/en.json" \
-F "file_tag_name=frontend"Richiesta con URL di callback:
curl -X PUT "https://app.ptc.wpml.org/api/v1/source_files/process" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file=@messages.po" \
-F "file_path=locales/messages.po" \
-F "callback_url=https://your-app.com/webhooks/translation-complete"Esempi di codice
curl -X PUT "https://app.ptc.wpml.org/api/v1/source_files/process" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file=@updated_translations.json" \
-F "file_path=src/locales/en.json" \
-F "file_tag_name=frontend" \
-F "callback_url=https://your-app.com/webhooks/complete"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files/process')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Put.new(uri)
request['Authorization'] = 'Bearer YOUR_API_TOKEN'
request.set_form(
[
['file', File.open('updated_translations.json')],
['file_path', 'src/locales/en.json'],
['file_tag_name', 'frontend'],
['callback_url', 'https://your-app.com/webhooks/complete']
],
'multipart/form-data'
)
response = http.request(request)
puts response.bodyimport requests
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}
files = {'file': open('updated_translations.json', 'rb')}
data = {
'file_path': 'src/locales/en.json',
'file_tag_name': 'frontend',
'callback_url': 'https://your-app.com/webhooks/complete'
}
response = requests.put('https://app.ptc.wpml.org/api/v1/source_files/process',
headers=headers, files=files, data=data)
print(response.json())<?php
$post_data = [
'file' => new CURLFile('updated_translations.json'),
'file_path' => 'src/locales/en.json',
'file_tag_name' => 'frontend',
'callback_url' => 'https://your-app.com/webhooks/complete'
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://app.ptc.wpml.org/api/v1/source_files/process',
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r(json_decode($response, true));
?>import okhttp3.*;
import java.io.File;
OkHttpClient client = new OkHttpClient();
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "updated_translations.json",
RequestBody.create(new File("updated_translations.json"), MediaType.parse("application/octet-stream")))
.addFormDataPart("file_path", "src/locales/en.json")
.addFormDataPart("file_tag_name", "frontend")
.addFormDataPart("callback_url", "https://your-app.com/webhooks/complete")
.build();
Request request = new Request.Builder()
.url("https://app.ptc.wpml.org/api/v1/source_files/process")
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.put(body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
file, _ := os.Open("updated_translations.json")
defer file.Close()
fw, _ := w.CreateFormFile("file", "updated_translations.json")
io.Copy(fw, file)
w.WriteField("file_path", "src/locales/en.json")
w.WriteField("file_tag_name", "frontend")
w.WriteField("callback_url", "https://your-app.com/webhooks/complete")
w.Close()
req, _ := http.NewRequest("PUT", "https://app.ptc.wpml.org/api/v1/source_files/process", &buf)
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
req.Header.Add("Content-Type", w.FormDataContentType())
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.IO;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_TOKEN");
var form = new MultipartFormDataContent();
form.Add(new StreamContent(File.OpenRead("updated_translations.json")), "file", "updated_translations.json");
form.Add(new StringContent("src/locales/en.json"), "file_path");
form.Add(new StringContent("frontend"), "file_tag_name");
form.Add(new StringContent("https://your-app.com/webhooks/complete"), "callback_url");
var response = await client.PutAsync("https://app.ptc.wpml.org/api/v1/source_files/process", form);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
form.append('file', fs.createReadStream('updated_translations.json'));
form.append('file_path', 'src/locales/en.json');
form.append('file_tag_name', 'frontend');
form.append('callback_url', 'https://your-app.com/webhooks/complete');
const response = await axios.put('https://app.ptc.wpml.org/api/v1/source_files/process', form, {
headers: {
...form.getHeaders(),
'Authorization': 'Bearer YOUR_API_TOKEN'
}
});
console.log(response.data);Formati di file supportati
L'endpoint supporta vari formati di file traducibili, tra cui file JSON, PO/POT, XLIFF e Properties, tra gli altri. La convalida del formato del file avviene durante il caricamento per garantire la compatibilità.
Usa l'endpoint Elenca i formati di file supportati per ottenere l'elenco completo dei formati supportati.
Ottieni lo stato della traduzione
Recupera l'avanzamento corrente della traduzione per un file di origine specifico, incluso quanto è stato completato e il suo stato di elaborazione complessivo.
Questo è utile per:
- Monitoraggio dei progressi – Monitorare l'avanzamento della traduzione per job di lunga durata
- Aggiornamenti dell'interfaccia utente – Visualizzare le percentuali di completamento nella tua applicazione
- Integrazione del flusso di lavoro – Attivare azioni quando la traduzione raggiunge una determinata soglia
Richiesta HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_statusParametri
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
file_path |
string | Sì | Il percorso del file di origine all'interno del progetto. |
file_tag_name |
string | No | Il nome del tag del file. Se non fornito, viene utilizzato il tag del file predefinito del progetto. |
Risposte
Risposta di successo
{
"translation_status": {
"status": "completed",
"completeness": 100
}
}Schema della risposta
| Campo | Tipo | Descrizione |
|---|---|---|
translation_status.status |
string | L'attuale stato di elaborazione del file di origine. Vedi i valori di stato di seguito. |
translation_status.completeness |
number | La percentuale di stringhe tradotte (0–100). Calcolata come (completed_translatable_strings / total_translatable_strings) × 100. |
Valori di stato
Il campo status può contenere i seguenti valori:
| Stato | Descrizione |
|---|---|
pending |
Il file di origine è in attesa di essere elaborato. |
processing |
La traduzione è attualmente in corso. |
completed |
Tutte le traduzioni sono state completate. |
failed |
Il processo di traduzione ha riscontrato degli errori. |
Risposte di errore
File di origine non trovato
{
"error": "Source file not found"
}Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Parametri non validi
{
"error": "Invalid parameters provided."
}Richieste di esempio
Richiesta di base:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_status?file_path=locales/en.po" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Richiesta con tag del file:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_status?file_path=locales/en.po&file_tag_name=frontend" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Esempi di codice
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/translation_status?file_path=locales/en.po&file_tag_name=frontend" \
-H "Authorization: Bearer YOUR_API_TOKEN"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files/translation_status')
uri.query = URI.encode_www_form(file_path: 'locales/en.po', file_tag_name: 'frontend')
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 "Translation #{data['translation_status']['completeness']}% complete"import requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
params = {
'file_path': 'locales/en.po',
'file_tag_name': 'frontend'
}
response = requests.get('https://app.ptc.wpml.org/api/v1/source_files/translation_status',
headers=headers, params=params)
data = response.json()
print(f"Translation {data['translation_status']['completeness']}% complete")<?php
$params = http_build_query([
'file_path' => 'locales/en.po',
'file_tag_name' => 'frontend'
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://app.ptc.wpml.org/api/v1/source_files/translation_status?{$params}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
echo "Translation " . $data['translation_status']['completeness'] . "% complete";
?>import okhttp3.*;
OkHttpClient client = new OkHttpClient();
HttpUrl url = HttpUrl.parse("https://app.ptc.wpml.org/api/v1/source_files/translation_status")
.newBuilder()
.addQueryParameter("file_path", "locales/en.po")
.addQueryParameter("file_tag_name", "frontend")
.build();
Request request = new Request.Builder()
.url(url)
.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/source_files/translation_status", nil)
q := req.URL.Query()
q.Add("file_path", "locales/en.po")
q.Add("file_tag_name", "frontend")
req.URL.RawQuery = q.Encode()
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/source_files/translation_status?file_path=locales/en.po&file_tag_name=frontend");
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/source_files/translation_status', {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' },
params: {
file_path: 'locales/en.po',
file_tag_name: 'frontend'
}
});
console.log(`Translation ${response.data.translation_status.completeness}% complete`);Scarica tutte le traduzioni
Scarica tutti i file tradotti per un file di origine specifico come archivio ZIP.
Questo endpoint crea e restituisce un archivio compresso contenente tutti i file di traduzione nelle lingue di destinazione per il file di origine specificato.
Se non sono disponibili traduzioni per il file, la richiesta restituirà un errore 404 Non trovato.
Richiesta HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/download_translationsParametri
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
file_path |
string | Sì | Il percorso del file di origine all'interno del progetto. |
file_tag_name |
string | No | Il nome del tag del file. Se non fornito, viene utilizzato il tag del file predefinito del progetto. Un file di origine è identificato in modo univoco dalla combinazione di file_path e file_tag_name. |
Risposte
Risposta di successo
{
"status": "processing",
"message": "Translations are still in progress. Please retry after the specified delay.",
"retry_after": 30
}PTC elabora le traduzioni in modo asincrono. Di solito c'è una breve attesa tra il caricamento di un file di origine e la disponibilità delle traduzioni per il download.
Quando ciò accade, attendi il numero di secondi specificato in Retry-After.
Risposte di errore
File di origine non trovato
{
"error": "Source file not found"
}Nessuna traduzione disponibile
{
"error": "No translations are available for this source file"
}Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Parametri non validi
{
"error": "Invalid parameters provided."
}Richieste di esempio
Richiesta di base:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=locales/en.po" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-o translations.zipRichiesta con tag del file:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=locales/en.po&file_tag_name=frontend" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-o frontend-translations.zipEsempi di codice
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=locales/en.po&file_tag_name=frontend" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-o translations.zip
# 200 -> saves the zip; 202 -> {"status":"processing","retry_after":N} (retry later);
# 404 -> {"error":"No translations are available for this source file"}require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files/download_translations')
uri.query = URI.encode_www_form(file_path: 'locales/en.po', file_tag_name: 'frontend')
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)
if response.code == '200'
File.binwrite('translations.zip', response.body)
puts 'Translations downloaded successfully'
elsif response.code == '202'
puts 'Translations are still processing — retry after the Retry-After interval'
elsif response.code == '404'
puts 'No translations are available for this source file yet'
endimport requests
headers = {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
params = {
'file_path': 'locales/en.po',
'file_tag_name': 'frontend'
}
response = requests.get('https://app.ptc.wpml.org/api/v1/source_files/download_translations',
headers=headers, params=params)
if response.status_code == 200:
with open('translations.zip', 'wb') as f:
f.write(response.content)
print('Translations downloaded successfully')
elif response.status_code == 202:
print('Translations are still processing — retry after the Retry-After interval')
elif response.status_code == 404:
print('No translations are available for this source file yet')<?php
$params = http_build_query([
'file_path' => 'locales/en.po',
'file_tag_name' => 'frontend'
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://app.ptc.wpml.org/api/v1/source_files/download_translations?{$params}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode === 200) {
file_put_contents('translations.zip', $response);
echo 'Translations downloaded successfully';
} elseif ($httpCode === 202) {
echo 'Translations are still processing — retry after the Retry-After interval';
} elseif ($httpCode === 404) {
echo 'No translations are available for this source file yet';
}
?>import okhttp3.*;
import java.nio.file.*;
OkHttpClient client = new OkHttpClient();
HttpUrl url = HttpUrl.parse("https://app.ptc.wpml.org/api/v1/source_files/download_translations")
.newBuilder()
.addQueryParameter("file_path", "locales/en.po")
.addQueryParameter("file_tag_name", "frontend")
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.build();
Response response = client.newCall(request).execute();
if (response.code() == 200) {
Files.write(Paths.get("translations.zip"), response.body().bytes());
System.out.println("Translations downloaded successfully");
} else if (response.code() == 202) {
System.out.println("Translations are still processing — retry after the Retry-After interval");
} else if (response.code() == 404) {
System.out.println("No translations are available for this source file yet");
}package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://app.ptc.wpml.org/api/v1/source_files/download_translations", nil)
q := req.URL.Query()
q.Add("file_path", "locales/en.po")
q.Add("file_tag_name", "frontend")
req.URL.RawQuery = q.Encode()
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
if resp.StatusCode == 200 {
body, _ := io.ReadAll(resp.Body)
os.WriteFile("translations.zip", body, 0644)
fmt.Println("Translations downloaded successfully")
} else if resp.StatusCode == 202 {
fmt.Println("Translations are still processing — retry after the Retry-After interval")
} else if resp.StatusCode == 404 {
fmt.Println("No translations are available for this source file yet")
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
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/source_files/download_translations?file_path=locales/en.po&file_tag_name=frontend");
if ((int)response.StatusCode == 200) {
var bytes = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes("translations.zip", bytes);
Console.WriteLine("Translations downloaded successfully");
} else if ((int)response.StatusCode == 202) {
Console.WriteLine("Translations are still processing — retry after the Retry-After interval");
} else if ((int)response.StatusCode == 404) {
Console.WriteLine("No translations are available for this source file yet");
}const axios = require('axios');
const fs = require('fs');
const response = await axios.get('https://app.ptc.wpml.org/api/v1/source_files/download_translations', {
headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' },
responseType: 'stream',
validateStatus: (s) => s === 200 || s === 202 || s === 404
});
if (response.status === 200) {
response.data.pipe(fs.createWriteStream('translations.zip'));
console.log('Translations downloaded successfully');
} else if (response.status === 202) {
console.log('Translations are still processing — retry after the Retry-After interval');
} else if (response.status === 404) {
console.log('No translations are available for this source file yet');
}Caricamento in blocco dei file di origine
Carica un archivio ZIP contenente più file traducibili. Ogni file nell'archivio viene estratto, convalidato ed elaborato. I formati supportati vengono identificati automaticamente.
Questa è la versione batch di Elabora il file di origine, progettata per velocizzare gli aggiornamenti su larga scala.
Informazioni aggiuntive
- Se un file corrisponde a un file di origine esistente, viene aggiornato con il nuovo contenuto e le traduzioni vengono attivate nuovamente.
- Se un file è supportato ma non corrisponde a nessun file di origine esistente, viene aggiunto all'elenco
not_found_filese ignorato. - I file con formati non supportati sono elencati sotto
unsupported_filese ignorati. - Anche i file con contenuto non valido sono elencati sotto
unsupported_filese ignorati. - L'elaborazione di archivi di grandi dimensioni potrebbe richiedere più tempo. I file vengono elaborati uno per uno per gestire le risorse, quindi è meglio suddividere i caricamenti molto grandi (più di 100 file) in batch più piccoli. Tutti i file nell'archivio sono impostati per essere tradotti automaticamente.
- Lo ZIP caricato deve essere valido e leggibile. Tutti i file all'interno devono essere in un formato supportato. I nomi dei file non devono includere caratteri speciali che potrebbero causare problemi di percorso.
- Se viene fornito un
callback_url, viene inviata una richiestaPOSTper ogni file di origine elaborato con i relativi risultati.
Richiesta HTTP
POST https://app.ptc.wpml.org/api/v1/source_files/bulkParametri
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
zip_file |
file | Sì | Un archivio ZIP contenente i file di origine da caricare. Deve essere un file ZIP valido. |
file_tag_name |
string | No | Il nome del tag del file da associare a tutti i file di origine nell'archivio. Se non specificato, viene utilizzato il tag del file predefinito del progetto. Ogni file di origine è identificato in modo univoco dalla combinazione di file_path e file_tag_name. |
callback_url |
string | No | L'URL che riceve le notifiche webhook quando ogni file viene elaborato. |
Struttura del file ZIP prevista
Il file ZIP può contenere file di origine in qualsiasi struttura di directory. La struttura delle directory viene mantenuta e i file vengono elaborati in modo ricorsivo.
Struttura ZIP di esempio:
source-files.zip
├── locales/
│ ├── messages-en.po
│ ├── validation-en.po
│ └── admin-en.po
├── frontend/
│ ├── components-en.json
│ └── pages-en.json
│ └── not-found-en.json
├── app-strings-en.properties
└── readme.txt (will be ignored)
Tipi di file supportati:
- JSON: file
.json - gettext: file
.po,.pot - Properties: file
.properties - YAML: file
.yml,.yaml - XML: file
.xml - Strings: file
.strings - XLIFF: file
.xliff,.xlf - CSV: file
.csv - PHP: file
.php
Risposte
Risposta di successo
{
"success": true,
"file_tag": {
"id": 456,
"name": "backend"
},
"processed_files": [
{
"id": 123,
"file_path": "locales/messages-en.po",
"created_at": "2024-01-15T10:30:00.000Z",
"file_tag": {
"id": 456,
"name": "backend"
}
},
{
"id": 124,
"file_path": "locales/validation-en.po",
"created_at": "2024-01-15T10:30:05.000Z",
"file_tag": {
"id": 456,
"name": "backend"
}
}
],
"unsupported_files": [
"readme.txt",
"config.ini"
],
"not_found_files": ["frontend/not-found-en.json"]
}Schema della risposta
| Campo | Tipo | Descrizione |
|---|---|---|
success |
boolean | Indica se l'operazione di caricamento in blocco è andata a buon fine. |
file_tag |
object | Le informazioni sul tag del file. |
file_tag.id |
integer | L'identificatore del tag del file. |
file_tag.name |
string | Il nome del tag del file. |
processed_files |
array[object] | Un array di file di origine che sono stati elaborati con successo. |
processed_files[].id |
integer | L'identificatore univoco del file di origine creato. |
processed_files[].file_path |
string | Il percorso del file di origine, mantenendo la struttura ZIP originale. |
processed_files[].created_at |
string | Un timestamp ISO 8601 che indica quando il file di origine è stato creato. |
processed_files[].file_tag |
object | Le informazioni sul tag del file. |
processed_files[].file_tag.id |
integer | L'identificatore del tag del file. |
processed_files[].file_tag.name |
string | Il nome del tag del file. |
unsupported_files |
array[string] | Un array di nomi di file che non sono in un formato supportato. |
not_found_files |
array[string] | Un array di file supportati che non corrispondevano a nessun file di origine esistente e sono stati ignorati. |
Risposte di errore
File ZIP non valido
{
"success": false,
"error": "File format is invalid",
"processed_files": [],
"unsupported_files": []
}Elaborazione non riuscita
{
"success": false,
"error": "Failed to process ZIP archive",
"processed_files": [],
"unsupported_files": []
}Non autorizzato
{
"error": "Unauthorized access. Please provide a valid API token."
}Accesso negato
{
"error": "Access denied. Insufficient permissions."
}Callback webhook
Quando viene fornito un callback_url, viene inviata una richiesta POST per ogni file elaborato.
Corpo della richiesta di callback (per file):
{
"source_file_id": 123,
"status": "completed",
"file_tag_name": "backend",
"download_url": "https://app.ptc.wpml.org/api/v1/source_files/download_translations?file_path=locales/messages-en.po&file_tag_name=backend",
"file_path": "locales/messages-en.po"
}Richieste di esempio
Caricamento in blocco di base:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files/bulk" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "zip_file=@source-files.zip" \
-F "file_tag_name=backend"Richiesta con URL di callback:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files/bulk" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "zip_file=@translations.zip" \
-F "file_tag_name=localization" \
-F "callback_url=https://your-app.com/webhooks/bulk-complete"Esempi di codice
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files/bulk" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "zip_file=@source-files.zip" \
-F "file_tag_name=backend" \
-F "callback_url=https://your-app.com/webhooks/complete"require 'net/http'
require 'uri'
uri = URI('https://app.ptc.wpml.org/api/v1/source_files/bulk')
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.set_form(
[
['zip_file', File.open('source-files.zip')],
['file_tag_name', 'backend'],
['callback_url', 'https://your-app.com/webhooks/complete']
],
'multipart/form-data'
)
response = http.request(request)
puts response.bodyimport requests
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}
files = {'zip_file': open('source-files.zip', 'rb')}
data = {
'file_tag_name': 'backend',
'callback_url': 'https://your-app.com/webhooks/complete'
}
response = requests.post('https://app.ptc.wpml.org/api/v1/source_files/bulk',
headers=headers, files=files, data=data)
print(response.json())<?php
$post_data = [
'zip_file' => new CURLFile('source-files.zip'),
'file_tag_name' => 'backend',
'callback_url' => 'https://your-app.com/webhooks/complete'
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://app.ptc.wpml.org/api/v1/source_files/bulk',
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN'
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r(json_decode($response, true));
?>import okhttp3.*;
import java.io.File;
OkHttpClient client = new OkHttpClient();
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("zip_file", "source-files.zip",
RequestBody.create(new File("source-files.zip"), MediaType.parse("application/octet-stream")))
.addFormDataPart("file_tag_name", "backend")
.addFormDataPart("callback_url", "https://your-app.com/webhooks/complete")
.build();
Request request = new Request.Builder()
.url("https://app.ptc.wpml.org/api/v1/source_files/bulk")
.addHeader("Authorization", "Bearer YOUR_API_TOKEN")
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
file, _ := os.Open("source-files.zip")
defer file.Close()
fw, _ := w.CreateFormFile("zip_file", "source-files.zip")
io.Copy(fw, file)
w.WriteField("file_tag_name", "backend")
w.WriteField("callback_url", "https://your-app.com/webhooks/complete")
w.Close()
req, _ := http.NewRequest("POST", "https://app.ptc.wpml.org/api/v1/source_files/bulk", &buf)
req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
req.Header.Add("Content-Type", w.FormDataContentType())
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.IO;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_TOKEN");
var form = new MultipartFormDataContent();
form.Add(new StreamContent(File.OpenRead("source-files.zip")), "zip_file", "source-files.zip");
form.Add(new StringContent("backend"), "file_tag_name");
form.Add(new StringContent("https://your-app.com/webhooks/complete"), "callback_url");
var response = await client.PostAsync("https://app.ptc.wpml.org/api/v1/source_files/bulk", form);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
form.append('zip_file', fs.createReadStream('source-files.zip'));
form.append('file_tag_name', 'backend');
form.append('callback_url', 'https://your-app.com/webhooks/complete');
const response = await axios.post('https://app.ptc.wpml.org/api/v1/source_files/bulk', form, {
headers: {
...form.getHeaders(),
'Authorization': 'Bearer YOUR_API_TOKEN'
}
});
console.log(response.data);Successivo:
Trova i formati di file e le lingue di destinazione supportati tramite l'API →