Suba y gestione archivos de origen a través de la API
Utilice esta API para subir nuevos archivos de origen, reemplazar los obsoletos, hacer un seguimiento del progreso de la traducción y descargar las traducciones completadas.
Tanto si gestiona un solo archivo como si automatiza un flujo de trabajo de localización continua, esta API le ofrece un control total sobre el contenido que envía para traducir y cómo recibe las traducciones.
Enlaces rápidos de la API
Cómo identifica y organiza los archivos de origen la API de PTC
La API de PTC utiliza un sistema flexible basado en etiquetas de archivo y rutas de archivo. Estos parámetros funcionan en conjunto para garantizar que cada archivo que suba, actualice o solicite esté claramente definido y sea fácil de gestionar.
Etiquetas de archivo
Las etiquetas de archivo son una forma flexible de agrupar y organizar los archivos de origen en los proyectos de traducción. Puede utilizarlas como categorías para adaptarlas a las necesidades de su flujo de trabajo. Por ejemplo, las etiquetas de archivo pueden indicar:
- Control de versiones:
v1.0,beta,production - Ramas de características:
user-auth,dashboard-redesign - Contexto de la aplicación:
mobile-app,admin-panel,marketing - Propiedad del equipo:
frontend-team,content-team - Estado del flujo de trabajo:
approved,pending-review,priority-high
Los nombres de las etiquetas de archivo son opcionales en la mayoría de las operaciones de la API. Sin embargo, cada archivo de origen siempre tiene al menos una etiqueta. Se crea y asigna automáticamente una etiqueta de archivo predeterminada al configurar un proyecto. Este comportamiento predeterminado mantiene los proyectos organizados incluso en configuraciones sencillas, al tiempo que le permite crear estructuras de etiquetado más avanzadas cuando sea necesario.
Nombre de la etiqueta de archivo + ruta del archivo
Cada archivo de origen se identifica de forma exclusiva mediante la combinación de su nombre de etiqueta de archivo y su ruta de archivo.
- Si no proporciona una etiqueta de archivo personalizada al subir o procesar un archivo, se asignará la etiqueta predeterminada automáticamente.
- El nombre de la etiqueta + la ruta de un archivo definen en conjunto su identidad. Esta combinación garantiza que cada archivo sea único dentro de su proyecto, incluso si diferentes versiones o contextos comparten la misma ruta de archivo.
Parámetros de consulta
Al recuperar un archivo específico, los endpoints relacionados pueden aceptar parámetros de consulta como:
file_tag_name: la etiqueta asociada al archivofile_path: la ruta del archivo
Estos parámetros le permiten localizar con precisión y recuperar los archivos correctos de su proyecto.
Listar todos los archivos de origen en el proyecto
Enumera todos los archivos de origen de su proyecto, con opciones para filtrar, ordenar y paginar los resultados. Esto resulta útil cuando desea explorar sus archivos, comprobar su estado o encontrar archivos específicos en función de la etiqueta, la ruta o el método de subida.
Petición HTTP
GET https://app.ptc.wpml.org/api/v1/source_filesParámetros
| Parámetro | Tipo | Obligatorio | Predeterminado | Descripción |
|---|---|---|---|---|
page |
entero | No | 1 |
El número de página para la paginación. Debe ser mayor que 0. |
per_page |
entero | No | 50 |
El número de elementos por página. Debe ser mayor que 0. |
order_by |
cadena | No | created_at |
El campo por el cual ordenar. Valores permitidos: id, created_at, updated_at. |
sort |
cadena | No | desc |
La dirección de ordenación. Valores permitidos: asc, desc. |
file_path |
cadena | No | – | Filtra por la ruta de archivo exacta. |
upload_origin |
cadena | No | – | Filtra por la forma en que se subió el archivo. Los valores permitidos incluyen: git, manual, api. |
Respuestas
Respuesta de éxito
{
"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
}
}Esquema de respuesta
Objeto del archivo de origen:
| Campo | Tipo | Descripción |
|---|---|---|
id |
entero | El identificador único del archivo de origen. |
file_path |
cadena | La ruta del archivo de origen dentro del proyecto. |
translation_path |
cadena | El patrón de dónde deben guardarse los archivos traducidos. |
additional_translation_files |
array[cadena] | Las rutas para cualquier archivo de salida adicional. |
status |
cadena | El estado de procesamiento actual del archivo de origen. |
upload_origin |
cadena | La forma en que se subió el archivo (git, manual, api). |
created_at |
cadena | Una marca de tiempo ISO 8601 que indica cuándo se creó originalmente el archivo de origen. |
updated_at |
cadena | Una marca de tiempo ISO 8601 que indica cuándo se actualizó por última vez el archivo de origen. |
file_tag |
objeto | Información sobre la etiqueta de archivo. |
file_tag.id |
entero | El identificador de la etiqueta de archivo. |
file_tag.name |
cadena | El nombre de la etiqueta de archivo. |
download_url |
cadena | La URL para descargar las traducciones de este archivo de origen. |
Objeto de paginación:
| Campo | Tipo | Descripción |
|---|---|---|
page |
entero | El número de página actual. |
per_page |
entero | El número de elementos por página. |
total |
entero | El número total de archivos de origen. |
total_pages |
entero | El número total de páginas. |
has_next_page |
booleano | Si hay una página siguiente disponible. |
has_previous_page |
booleano | Si hay una página anterior disponible. |
Respuestas de error
No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Parámetros no válidos
{
"error": "Invalid parameters provided."
}Peticiones de ejemplo
Petición básica:
curl -X GET "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json"Petición filtrada:
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"Ejemplos de código
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);Obtener cadenas de traducción
Recupera todas las cadenas traducibles de un archivo de origen específico, junto con sus traducciones existentes en todos los idiomas de destino.
Este endpoint es útil para obtener contenido que necesita ser traducido o que ya ha sido traducido. El archivo de origen se identifica mediante file_path y file_tag_name.
Petición HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_stringsParámetros
| Parámetro | Tipo | Obligatorio | Predeterminado | Descripción |
|---|---|---|---|---|
file_path |
cadena | Sí | – | La ruta del archivo de origen dentro del proyecto. |
file_tag_name |
cadena | No | – | El nombre de la etiqueta de archivo. Si no se proporciona, se utiliza la etiqueta predeterminada del proyecto. |
page |
entero | No | 1 |
El número de página para la paginación (utilizado como cursor). Debe ser mayor que 0. |
q |
cadena | No | – | La consulta de búsqueda para filtrar las cadenas de traducción por su texto de origen. |
Respuestas
Respuesta de éxito
{
"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
}Esquema de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
total_strings_count |
entero | El número total de cadenas traducibles en el archivo de origen. |
translation_strings |
array[objeto] | El array de objetos de cadenas de traducción (paginado, máximo 500 por página). |
translation_strings[].source |
cadena | El texto de origen original que se va a traducir. |
translation_strings[].translations |
objeto | Un hash de traducciones donde las claves son códigos ISO de idiomas y los valores son el texto traducido. |
cursor |
entero | El cursor de página actual utilizado para la paginación. |
Respuestas de error
Archivo de origen no encontrado
{
"error": "Source file not found"
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Parámetros no válidos
{
"error": "Invalid parameters provided."
}Peticiones de ejemplo
Petición básica:
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 petición con etiqueta de archivo:
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 petición con paginación y búsqueda:
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"Ejemplos de código
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);Crear el archivo de origen
Registra un nuevo archivo de origen en su proyecto para que esté listo para traducir.
Este endpoint crea la entrada del archivo y establece su configuración de traducción, pero no adjunta el contenido real del archivo.
Después de crear el archivo, deberá utilizar el endpoint Procesar el archivo de origen para subir el contenido e iniciar el proceso de traducción.
Petición HTTP
POST https://app.ptc.wpml.org/api/v1/source_filesParámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
file_path |
cadena | Sí | La ruta donde debe almacenarse el archivo de origen en el proyecto. Debe tener una extensión compatible. |
output_file_path |
cadena | Sí | El patrón de ruta de salida para los archivos traducidos. Utilice {{lang}} como marcador de posición para el código de idioma. |
translations |
array[objeto] | No | Los archivos de traducción preexistentes que se subirán junto con el archivo de origen. Estos archivos se almacenarán tal como se proporcionan, y sus cadenas no serán retraducidas por PTC. Tenga en cuenta que no se recomienda proporcionar traducciones existentes, ya que PTC produce mejores resultados cuando puede utilizar el contexto completo de su proyecto y traducir desde cero. |
translations[].target_language_iso |
cadena | Sí | El código ISO del idioma de destino para esta traducción. Puede encontrar la lista completa de idiomas compatibles y sus códigos ISO en el endpoint Listar todos los idiomas de destino. |
translations[].file |
archivo | Sí | El archivo de traducción que se va a subir. |
additional_translation_files |
array[objeto] | No | Configuraciones de archivos de salida adicionales para formatos específicos. Para ver qué formatos admiten archivos de salida adicionales, consulte el endpoint Listar formatos de archivo compatibles. Para los formatos no compatibles, este campo se ignorará. |
additional_translation_files[].type |
cadena | Sí | Consulte los formatos de archivo compatibles para obtener más detalles. |
additional_translation_files[].path |
cadena | Sí | El patrón de ruta para el archivo. |
Respuestas
Respuesta de éxito
{
"source_file": {
"id": 123,
"file_path": "src/locales/en.json",
"created_at": "2024-01-15T10:30:00.000Z",
"file_tag": {
"id": 456,
"name": "frontend"
}
}
}Esquema de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
source_file.id |
entero | El identificador único del archivo de origen creado. |
source_file.file_path |
cadena | La ruta del archivo de origen dentro del proyecto. |
source_file.created_at |
cadena | Una marca de tiempo ISO 8601 que indica cuándo se creó originalmente el archivo de origen. |
source_file.file_tag.id |
entero | El identificador de la etiqueta de archivo. |
source_file.file_tag.name |
cadena | El nombre de la etiqueta de archivo. |
Respuestas de error
Fallo de validación
{
"success": false,
"error": "Source file creation failed"
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Peticiones de ejemplo
Creación básica de archivo de origen:
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"Petición con URL de callback:
curl -X POST "https://app.ptc.wpml.org/api/v1/source_files" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "file_path=src/locales/messages.po" \
-F "output_file_path=locales/{{lang}}/messages.po" \
-F "callback_url=https://your-app.com/webhooks/translation-complete"Petición con traducciones preexistentes:
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"Petición con archivos de salida adicionales:
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"Ejemplos de código
- JavaScript (FormData)
- Python (requests)
- PHP (cURL)
- Node.js (axios)
- Cuerpo de la petición de 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"
}Procesar el archivo de origen
Sube contenido a un archivo de origen existente e inicia el proceso de traducción.
Este endpoint reemplaza el contenido actual del archivo, actualiza las cadenas traducibles almacenadas e inicia la traducción automática.
Para utilizar este endpoint, el archivo de origen ya debe existir en el proyecto. Si aún no lo ha creado, consulte Crear el archivo de origen.
Petición HTTP
PUT https://app.ptc.wpml.org/api/v1/source_files/processParámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
file |
archivo | Sí | El archivo de origen que se va a subir. El contenido del archivo se valida para garantizar que coincida con su extensión declarada. Por ejemplo, si la extensión del archivo es .json, el contenido subido debe ser un archivo JSON válido. |
file_path |
cadena | Sí | La ruta al archivo de origen existente en el proyecto que debe actualizarse. |
file_tag_name |
cadena | No | El nombre de la etiqueta de archivo asociada al archivo de origen. Si no se proporciona, se utiliza la etiqueta de archivo predeterminada del proyecto. |
callback_url |
cadena | No | La URL que recibe notificaciones de webhook cuando se completa el procesamiento del archivo. |
Respuestas
Respuesta de éxito
{
"source_file": {
"id": 123,
"file_path": "src/locales/en.json",
"created_at": "2024-01-15T10:30:00.000Z",
"file_tag": {
"id": 456,
"name": "frontend"
}
}
}Esquema de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
source_file.id |
entero | El identificador único del archivo de origen procesado. |
source_file.file_path |
cadena | La ruta del archivo de origen dentro del proyecto. |
source_file.created_at |
cadena | Una marca de tiempo ISO 8601 que indica cuándo se creó originalmente el archivo de origen. |
source_file.file_tag.id |
entero | El identificador de la etiqueta de archivo. |
source_file.file_tag.name |
cadena | El nombre de la etiqueta de archivo. |
Respuestas de error
Archivo de origen no encontrado
{
"errors": {
"file": ["File format is invalid or not supported"]
}
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Flujo de trabajo
- Requisito previo: El archivo de origen ya debe estar creado mediante Crear el archivo de origen.
- Subida del archivo: Se sube el contenido nuevo y se reemplaza el contenido existente del archivo.
- Procesamiento: Las nuevas cadenas traducibles se extraen y se traducen automáticamente.
- Callback: Se envía una notificación de webhook opcional cuando finaliza el procesamiento.
Callback de webhook
Cuando se proporciona una callback_url, PTC enviará una petición POST a esa URL cuando se complete el procesamiento.
Cuerpo de la petición de 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"
}Peticiones de ejemplo
Procesamiento básico de archivo:
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"Petición con URL de 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"Ejemplos de código
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);Formatos de archivo compatibles
El endpoint admite varios formatos de archivo traducibles, como JSON, PO/POT, XLIFF y archivos Properties, entre otros. La validación del formato de archivo se produce durante la subida para garantizar la compatibilidad.
Utilice el endpoint Listar formatos de archivo compatibles para obtener la lista completa de formatos compatibles.
Obtener el estado de la traducción
Recupera el progreso de traducción actual para un archivo de origen específico, incluyendo cuánto se ha completado y su estado de procesamiento general.
Esto es útil para:
- Monitorización del progreso: hacer un seguimiento del progreso de la traducción en trabajos de larga duración
- Actualizaciones de la interfaz de usuario: mostrar porcentajes de finalización en su aplicación
- Integración del flujo de trabajo: desencadenar acciones cuando la traducción alcanza un umbral definido
Petición HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_statusParámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
file_path |
cadena | Sí | La ruta del archivo de origen dentro del proyecto. |
file_tag_name |
cadena | No | El nombre de la etiqueta de archivo. Si no se proporciona, se utiliza la etiqueta de archivo predeterminada del proyecto. |
Respuestas
Respuesta de éxito
{
"translation_status": {
"status": "completed",
"completeness": 100
}
}Esquema de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
translation_status.status |
cadena | El estado de procesamiento actual del archivo de origen. Vea los valores de estado a continuación. |
translation_status.completeness |
número | El porcentaje de cadenas traducidas (0–100). Se calcula como (completed_translatable_strings / total_translatable_strings) × 100. |
Valores de estado
El campo status puede contener los siguientes valores:
| Estado | Descripción |
|---|---|
pending |
El archivo de origen está a la espera de ser procesado. |
processing |
La traducción está actualmente en curso. |
completed |
Se han completado todas las traducciones. |
failed |
El proceso de traducción se ha encontrado con errores. |
Respuestas de error
Archivo de origen no encontrado
{
"error": "Source file not found"
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Parámetros no válidos
{
"error": "Invalid parameters provided."
}Peticiones de ejemplo
Petición básica:
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"Petición con etiqueta de archivo:
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"Ejemplos de código
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`);Descargar todas las traducciones
Descarga todos los archivos traducidos para un archivo de origen específico como un archivo comprimido ZIP.
Este endpoint crea y devuelve un archivo comprimido que contiene todos los archivos de traducción en los idiomas de destino para el archivo de origen especificado.
Si no hay traducciones disponibles para el archivo, la petición devolverá un error 404 No encontrado.
Petición HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/download_translationsParámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
file_path |
cadena | Sí | La ruta del archivo de origen dentro del proyecto. |
file_tag_name |
cadena | No | El nombre de la etiqueta de archivo. Si no se proporciona, se utiliza la etiqueta de archivo predeterminada del proyecto. Un archivo de origen se identifica de forma exclusiva mediante la combinación de file_path y file_tag_name. |
Respuestas
Respuesta de éxito
{
"status": "processing",
"message": "Translations are still in progress. Please retry after the specified delay.",
"retry_after": 30
}PTC procesa las traducciones de forma asíncrona. Por lo general, hay una breve espera entre la subida de un archivo de origen y la disponibilidad de las traducciones para descargar.
Cuando esto ocurra, espere el número de segundos especificado en Retry-After.
Respuestas de error
Archivo de origen no encontrado
{
"error": "Source file not found"
}No hay traducciones disponibles
{
"error": "No translations are available for this source file"
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Parámetros no válidos
{
"error": "Invalid parameters provided."
}Peticiones de ejemplo
Petición básica:
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.zipPetición con etiqueta de archivo:
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.zipEjemplos de código
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');
}Subir archivos de origen por lotes
Sube un archivo comprimido ZIP que contiene múltiples archivos traducibles. Cada archivo del archivo comprimido se extrae, se valida y se procesa. Los formatos compatibles se identifican automáticamente.
Esta es la versión por lotes de Procesar el archivo de origen, diseñada para acelerar las actualizaciones a gran escala.
Información adicional
- Si un archivo coincide con un archivo de origen existente, se actualiza con el nuevo contenido y las traducciones se desencadenan de nuevo.
- Si un archivo es compatible pero no coincide con ningún archivo de origen existente, se añade a la lista
not_found_filesy se ignora. - Los archivos con formatos no compatibles se enumeran en
unsupported_filesy se ignoran. - Los archivos con contenido no válido también se enumeran en
unsupported_filesy se ignoran. - Los archivos comprimidos grandes pueden tardar más en procesarse. Los archivos se procesan uno a uno para gestionar los recursos, por lo que es mejor dividir las subidas muy grandes (más de 100 archivos) en lotes más pequeños. Todos los archivos del archivo comprimido se configuran para traducirse automáticamente.
- El archivo ZIP subido debe ser válido y legible. Todos los archivos que contiene deben estar en un formato compatible. Los nombres de archivo no deben incluir caracteres especiales que puedan causar problemas de ruta.
- Si se proporciona una
callback_url, se envía una peticiónPOSTpara cada archivo de origen procesado con sus resultados.
Petición HTTP
POST https://app.ptc.wpml.org/api/v1/source_files/bulkParámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
zip_file |
archivo | Sí | Un archivo comprimido ZIP que contiene los archivos de origen que se van a subir. Debe ser un archivo ZIP válido. |
file_tag_name |
cadena | No | El nombre de la etiqueta de archivo que se asociará a todos los archivos de origen del archivo comprimido. Si no se especifica, se utiliza la etiqueta de archivo predeterminada del proyecto. Cada archivo de origen se identifica de forma exclusiva mediante la combinación de file_path y file_tag_name. |
callback_url |
cadena | No | La URL que recibe notificaciones de webhook cuando se procesa cada archivo. |
Estructura esperada del archivo ZIP
El archivo ZIP puede contener archivos de origen en cualquier estructura de directorios. La estructura de directorios se conserva y los archivos se procesan de forma recursiva.
Estructura ZIP de ejemplo:
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)
Tipos de archivo compatibles:
- JSON: archivos
.json - gettext: archivos
.po,.pot - Properties: archivos
.properties - YAML: archivos
.yml,.yaml - XML: archivos
.xml - Strings: archivos
.strings - XLIFF: archivos
.xliff,.xlf - CSV: archivos
.csv - PHP: archivos
.php
Respuestas
Respuesta de éxito
{
"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"]
}Esquema de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
success |
booleano | Si la operación de subida por lotes se realizó correctamente. |
file_tag |
objeto | La información de la etiqueta de archivo. |
file_tag.id |
entero | El identificador de la etiqueta de archivo. |
file_tag.name |
cadena | El nombre de la etiqueta de archivo. |
processed_files |
array[objeto] | Un array de archivos de origen que se procesaron correctamente. |
processed_files[].id |
entero | El identificador único del archivo de origen creado. |
processed_files[].file_path |
cadena | La ruta del archivo de origen, conservando la estructura ZIP original. |
processed_files[].created_at |
cadena | Una marca de tiempo ISO 8601 que indica cuándo se creó el archivo de origen. |
processed_files[].file_tag |
objeto | La información de la etiqueta de archivo. |
processed_files[].file_tag.id |
entero | El identificador de la etiqueta de archivo. |
processed_files[].file_tag.name |
cadena | El nombre de la etiqueta de archivo. |
unsupported_files |
array[cadena] | Un array de nombres de archivo que no tienen un formato compatible. |
not_found_files |
array[cadena] | Un array de archivos compatibles que no coincidieron con ningún archivo de origen existente y fueron ignorados. |
Respuestas de error
Archivo ZIP no válido
{
"success": false,
"error": "File format is invalid",
"processed_files": [],
"unsupported_files": []
}Fallo de procesamiento
{
"success": false,
"error": "Failed to process ZIP archive",
"processed_files": [],
"unsupported_files": []
}No autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Prohibido
{
"error": "Access denied. Insufficient permissions."
}Callback de webhook
Cuando se proporciona una callback_url, se envía una petición POST por cada archivo procesado.
Cuerpo de la petición de callback (por archivo):
{
"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"
}Peticiones de ejemplo
Subida básica por lotes:
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"Petición con URL de 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"Ejemplos de código
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);Siguiente:
Buscar formatos de archivo compatibles e idiomas de destino a través de la API →