Envie e gerencie arquivos de origem via API
Use esta API para enviar novos arquivos de origem, substituir os desatualizados, acompanhar o progresso da tradução e baixar as traduções concluídas.
Quer você esteja gerenciando um único arquivo ou automatizando um fluxo de localização contínua, esta API oferece controle total sobre o conteúdo que você envia para tradução e como recebe as traduções.
Links rápidos da API
Como a API da PTC identifica e organiza os arquivos de origem
A API da PTC usa um sistema flexível baseado em tags de arquivo e caminhos de arquivo. Esses parâmetros trabalham juntos para garantir que cada arquivo que você envia, atualiza ou solicita seja claramente definido e fácil de gerenciar.
Tags de arquivo
As tags de arquivo são uma maneira flexível de agrupar e organizar arquivos de origem em projetos de tradução. Você pode usá-las como categorias para atender às necessidades do seu fluxo de trabalho. Por exemplo, as tags de arquivo podem indicar:
- Controle de versão:
v1.0,beta,production - Branches de recursos:
user-auth,dashboard-redesign - Contexto do aplicativo:
mobile-app,admin-panel,marketing - Propriedade da equipe:
frontend-team,content-team - Estado do fluxo de trabalho:
approved,pending-review,priority-high
Os nomes das tags de arquivo são opcionais na maioria das operações da API. No entanto, todo arquivo de origem sempre tem pelo menos uma tag. Uma tag de arquivo padrão é criada e atribuída automaticamente quando um projeto é configurado. Esse comportamento padrão mantém os projetos organizados mesmo em configurações simples, ao mesmo tempo que permite que você crie estruturas de tags mais avançadas quando necessário.
Nome da tag de arquivo + Caminho do arquivo
Cada arquivo de origem é identificado de forma exclusiva pela combinação do seu nome da tag de arquivo e caminho do arquivo.
- Se você não fornecer uma tag de arquivo personalizada ao enviar ou processar um arquivo, a tag padrão será atribuída automaticamente.
- O nome da tag + o caminho de um arquivo definem juntos a sua identidade. Essa combinação garante que cada arquivo seja único dentro do seu projeto, mesmo que diferentes versões ou contextos compartilhem o mesmo caminho de arquivo.
Parâmetros de consulta
Ao recuperar um arquivo específico, os endpoints relacionados podem aceitar parâmetros de consulta, como:
file_tag_name– A tag associada ao arquivofile_path– O caminho para o arquivo
Esses parâmetros permitem que você localize e recupere com precisão os arquivos corretos do seu projeto.
Listar todos os arquivos de origem no projeto
Lista todos os arquivos de origem no seu projeto, com opções para filtrar, classificar e paginar os resultados. Isso é útil quando você deseja navegar pelos seus arquivos, verificar o status deles ou encontrar arquivos específicos com base na tag, no caminho ou no método de envio.
Requisição HTTP
GET https://app.ptc.wpml.org/api/v1/source_filesParâmetros
| Parâmetro | Tipo | Obrigatório | Padrão | Descrição |
|---|---|---|---|---|
page |
integer | Não | 1 |
O número da página para paginação. Deve ser maior que 0. |
per_page |
integer | Não | 50 |
O número de itens por página. Deve ser maior que 0. |
order_by |
string | Não | created_at |
O campo pelo qual ordenar. Valores permitidos: id, created_at, updated_at. |
sort |
string | Não | desc |
A direção da ordenação. Valores permitidos: asc, desc. |
file_path |
string | Não | – | Filtra pelo caminho do arquivo exato. |
upload_origin |
string | Não | – | Filtra por como o arquivo foi enviado. Os valores permitidos incluem: git, manual, api. |
Respostas
Resposta de sucesso
{
"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 da resposta
Objeto do arquivo de origem:
| Campo | Tipo | Descrição |
|---|---|---|
id |
integer | O identificador exclusivo do arquivo de origem. |
file_path |
string | O caminho para o arquivo de origem dentro do projeto. |
translation_path |
string | O padrão para onde os arquivos traduzidos devem ser salvos. |
additional_translation_files |
array[string] | Os caminhos para quaisquer arquivos de saída adicionais. |
status |
string | O status de processamento atual do arquivo de origem. |
upload_origin |
string | Como o arquivo foi enviado (git, manual, api). |
created_at |
string | Um timestamp ISO 8601 indicando quando o arquivo de origem foi criado originalmente. |
updated_at |
string | Um timestamp ISO 8601 indicando quando o arquivo de origem foi atualizado pela última vez. |
file_tag |
object | Informações sobre a tag de arquivo. |
file_tag.id |
integer | O identificador da tag de arquivo. |
file_tag.name |
string | O nome da tag de arquivo. |
download_url |
string | A URL para baixar as traduções deste arquivo de origem. |
Objeto de paginação:
| Campo | Tipo | Descrição |
|---|---|---|
page |
integer | O número da página atual. |
per_page |
integer | O número de itens por página. |
total |
integer | O número total de arquivos de origem. |
total_pages |
integer | O número total de páginas. |
has_next_page |
boolean | Se há uma próxima página disponível. |
has_previous_page |
boolean | Se há uma página anterior disponível. |
Respostas de erro
Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Parâmetros inválidos
{
"error": "Invalid parameters provided."
}Exemplos de requisição
Requisição 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"Requisição 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"Exemplos 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);Obter strings de tradução
Recupera todas as strings traduzíveis de um arquivo de origem específico, junto com suas traduções existentes em todos os idiomas de destino.
Este endpoint é útil para buscar conteúdo que precisa ser traduzido ou que já foi traduzido. O arquivo de origem é identificado por file_path e file_tag_name.
Requisição HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_stringsParâmetros
| Parâmetro | Tipo | Obrigatório | Padrão | Descrição |
|---|---|---|---|---|
file_path |
string | Sim | – | O caminho para o arquivo de origem dentro do projeto. |
file_tag_name |
string | Não | – | O nome da tag de arquivo. Se não for fornecido, a tag padrão do projeto será usada. |
page |
integer | Não | 1 |
O número da página para paginação (usado como cursor). Deve ser maior que 0. |
q |
string | Não | – | A consulta de pesquisa para filtrar as strings de tradução pelo seu texto de origem. |
Respostas
Resposta de sucesso
{
"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 da resposta
| Campo | Type | Descrição |
|---|---|---|
total_strings_count |
integer | O número total de strings traduzíveis no arquivo de origem. |
translation_strings |
array[object] | O array de objetos de string de tradução (paginado, máximo de 500 por página). |
translation_strings[].source |
string | O texto de origem original a ser traduzido. |
translation_strings[].translations |
object | Um hash de traduções onde as chaves são os códigos ISO dos idiomas e os valores são o texto traduzido. |
cursor |
integer | O cursor da página atual usado para paginação. |
Respostas de erro
Arquivo de origem não encontrado
{
"error": "Source file not found"
}Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Parâmetros inválidos
{
"error": "Invalid parameters provided."
}Exemplos de requisição
Requisição 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"Uma requisição com tag de arquivo:
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"Uma requisição com paginação e busca:
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"Exemplos 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);Criar o arquivo de origem
Registra um novo arquivo de origem no seu projeto para que ele fique pronto para tradução.
Este endpoint cria a entrada do arquivo e define sua configuração de tradução, mas não anexa o conteúdo real do arquivo.
Após criar o arquivo, você precisará usar o endpoint processar o arquivo de origem para enviar o conteúdo e iniciar o processo de tradução.
Requisição HTTP
POST https://app.ptc.wpml.org/api/v1/source_filesParâmetros
| Parâmetro | Type | Obrigatório | Descrição |
|---|---|---|---|
file_path |
string | Sim | O caminho onde o arquivo de origem deve ser armazenado no projeto. Deve ter uma extensão suportada. |
output_file_path |
string | Sim | O padrão de caminho de saída para arquivos traduzidos. Use {{lang}} como um placeholder para o código do idioma. |
file_tag_name |
string | Não | O nome da tag de arquivo sob a qual registrar o arquivo de origem. Se não for fornecido, a tag de arquivo padrão do projeto será usada. |
translations |
array[object] | Não | Os arquivos de tradução pré-existentes para enviar junto com o arquivo de origem. Estes arquivos serão armazenados conforme fornecidos, e suas strings não serão retraduzidas pela PTC. Note que fornecer traduções existentes não é recomendado, pois a PTC produz resultados melhores quando pode usar o contexto completo do seu projeto e traduzir do zero. |
translations[].target_language_iso |
string | Sim | O código ISO do idioma de destino para esta tradução. Você pode encontrar a lista completa de idiomas suportados e seus códigos ISO no endpoint Listar todos os idiomas de destino. |
translations[].file |
file | Sim | O arquivo de tradução para enviar. |
additional_translation_files |
array[object] | Não | Configurações de arquivos de saída adicionais para formatos específicos. Para ver quais formatos suportam arquivos de saída adicionais, consulte o endpoint Listar formatos de arquivo suportados. Para formatos não suportados, este campo será ignorado. |
additional_translation_files[].type |
string | Sim | Veja os formatos de arquivo suportados para mais detalhes. |
additional_translation_files[].path |
string | Sim | O padrão de caminho para o arquivo. |
Respostas
Resposta de sucesso
{
"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 da resposta
| Campo | Type | Descrição |
|---|---|---|
source_file.id |
integer | O identificador único para o arquivo de origem criado. |
source_file.file_path |
string | O caminho do arquivo de origem dentro do projeto. |
source_file.created_at |
string | Um timestamp ISO 8601 indicando quando o arquivo de origem foi originalmente criado. |
source_file.file_tag.id |
integer | O identificador da tag de arquivo. |
source_file.file_tag.name |
string | O nome da tag de arquivo. |
Respostas de erro
Falha na validação
{
"success": false,
"error": "Source file creation failed"
}Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Exemplos de requisições
Criação básica de arquivo de origem:
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"O endpoint Create não aceita callback_url. O registro de um arquivo de origem não inicia nenhuma tradução, portanto não há nada para um callback anunciar — em vez disso, passe-o para Processar o arquivo de origem ou para Enviar arquivos de origem em lote, que são as chamadas que iniciam o trabalho.
Requisição com traduções pré-existentes:
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"Requisição com arquivos de saída adicionais:
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"Exemplos de código
- JavaScript (FormData)
- Python (requests)
- PHP (cURL)
- Node.js (axios)
- Corpo da requisição 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"
}Processar o arquivo de origem
Envia conteúdo para um arquivo de origem existente e inicia o processo de tradução.
Este endpoint substitui o conteúdo atual do arquivo, atualiza as strings traduzíveis armazenadas e inicia a tradução automática.
Para usar este endpoint, o arquivo de origem já deve existir no projeto. Se você ainda não o criou, consulte Criar o arquivo de origem.
Requisição HTTP
PUT https://app.ptc.wpml.org/api/v1/source_files/processParâmetros
| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
file |
file | Sim | O arquivo de origem a ser enviado. O conteúdo do arquivo é validado para garantir que corresponda à sua extensão declarada. Por exemplo, se a extensão do arquivo for .json, o conteúdo enviado deve ser um JSON válido. |
file_path |
string | Sim | O caminho para o arquivo de origem existente no projeto que deve ser atualizado. |
file_tag_name |
string | Não | O nome da tag de arquivo associada ao arquivo de origem. Se não for fornecido, a tag de arquivo padrão do projeto será usada. |
callback_url |
string | Não | A URL que recebe notificações de webhook quando o processamento do arquivo é concluído. |
Respostas
Resposta de sucesso
{
"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 resposta
| Campo | Tipo | Descrição |
|---|---|---|
source_file.id |
integer | O identificador único do arquivo de origem processado. |
source_file.file_path |
string | O caminho do arquivo de origem dentro do projeto. |
source_file.created_at |
string | Um timestamp ISO 8601 indicando quando o arquivo de origem foi originalmente criado. |
source_file.file_tag.id |
integer | O identificador da tag de arquivo. |
source_file.file_tag.name |
string | O nome da tag de arquivo. |
Respostas de erro
Formato de arquivo não suportado ou inválido
O Process substitui o conteúdo do arquivo pelo que você envia, portanto não há busca que possa falhar — este endpoint não tem caso de arquivo não encontrado. A única rejeição que ele retorna é na verificação de conteúdo do arquivo enviado.
{
"success": false,
"message": "Unprocessable Entity",
"code": 422,
"errors": [9001]
}errors é um array de códigos numéricos, não um objeto com chaves de campo. 9001 significa que o conteúdo não foi analisado como o formato que sua extensão alega. Algumas rejeições adicionam um objeto additional_info junto com os detalhes específicos.
Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Fluxo de trabalho
- Pré-requisito: O arquivo de origem já deve estar criado via criar o arquivo de origem.
- Upload de arquivo: O novo conteúdo é enviado e substitui o conteúdo existente do arquivo.
- Processamento: As novas strings traduzíveis são extraídas e traduzidas automaticamente.
- Callback: Uma notificação opcional de webhook é enviada quando o processamento termina.
Callback de webhook
Quando um callback_url é fornecido, a PTC enviará uma solicitação POST para essa URL quando o processamento for concluído.
Corpo da solicitação 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"
}Exemplos de solicitações
Processamento básico de arquivo:
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"Solicitação com 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"Exemplos 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 arquivo suportados
O endpoint suporta vários formatos de arquivo traduzíveis, incluindo JSON, PO/POT, XLIFF e arquivos Properties, entre outros. A validação do formato do arquivo ocorre durante o upload para garantir a compatibilidade.
Use o endpoint Listar formatos de arquivo suportados para obter a lista completa de formatos suportados.
Obter o status da tradução
Recupera o progresso atual da tradução para um arquivo de origem específico, incluindo o quanto foi concluído e seu status geral de processamento.
Isso é útil para:
- Monitoramento de progresso – Acompanhar o progresso da tradução para tarefas de longa duração
- Atualizações de UI – Exibir porcentagens de conclusão em seu aplicativo
- Integração de fluxo de trabalho – Acionar ações quando a tradução atingir um limite definido
Solicitação HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/translation_statusParâmetros
| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
file_path |
string | Sim | O caminho para o arquivo de origem dentro do projeto. |
file_tag_name |
string | Não | O nome da tag de arquivo. Se não for fornecido, a tag de arquivo padrão do projeto será usada. |
Respostas
Resposta de sucesso
{
"translation_status": {
"status": "completed",
"completeness": 100
}
}Esquema de resposta
| Campo | Tipo | Descrição |
|---|---|---|
translation_status.status |
string | O status de processamento atual do arquivo de origem. Veja os valores de status abaixo. |
translation_status.completeness |
number | A porcentagem de strings traduzidas (0–100). Calculada como (completed_translatable_strings / total_translatable_strings) × 100. |
Valores de status
O campo status pode conter os seguintes valores:
| Status | Descrição |
|---|---|
pending |
O arquivo de origem está aguardando para ser processado. |
processing |
A tradução está em andamento. |
completed |
Todas as traduções foram concluídas. |
failed |
O processo de tradução encontrou erros. |
Respostas de erro
Arquivo de origem não encontrado
{
"error": "Source file not found"
}Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Parâmetros inválidos
{
"error": "Invalid parameters provided."
}Exemplos de solicitações
Solicitação 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"Solicitação com tag de arquivo:
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"Exemplos 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`);Baixar todas as traduções
Baixa todos os arquivos traduzidos para um arquivo de origem específico como um arquivo ZIP.
Este endpoint cria e retorna um arquivo compactado contendo todos os arquivos de tradução nos idiomas de destino para o arquivo de origem especificado.
Se não houver traduções disponíveis para o arquivo, a solicitação retornará um erro 404 Not Found.
Solicitação HTTP
GET https://app.ptc.wpml.org/api/v1/source_files/download_translationsParâmetros
| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
file_path |
string | Sim | O caminho para o arquivo de origem dentro do projeto. |
file_tag_name |
string | Não | O nome da tag de arquivo. Se não for fornecido, a tag de arquivo padrão do projeto será usada. Um arquivo de origem é identificado de forma exclusiva pela combinação de file_path e file_tag_name. |
Respostas
Resposta de sucesso
{
"status": "processing",
"message": "Translations are still in progress. Please retry after the specified delay.",
"retry_after": 30
}A PTC processa as traduções de forma assíncrona. Geralmente, há uma pequena espera entre o envio de um arquivo de origem e a disponibilidade das traduções para download.
Quando isso acontecer, aguarde o número de segundos especificado em Retry-After.
Respostas de erro
Arquivo de origem não encontrado
{
"error": "Source file not found"
}Nenhuma tradução disponível
{
"error": "No translations are available for this source file"
}Não autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Parâmetros inválidos
{
"error": "Invalid parameters provided."
}Exemplos de requisições
Requisição 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.zipRequisição com tag de arquivo:
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.zipExemplos 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');
}Enviar arquivos de origem em lote
Envia um arquivo ZIP contendo vários arquivos traduzíveis. Cada arquivo no pacote é extraído, validado e processado. Os formatos suportados são identificados automaticamente.
Esta é a versão em lote de Processar o arquivo de origem, projetada para acelerar atualizações em grande escala.
Informações adicionais
- Se um arquivo corresponder a um arquivo de origem existente, ele será atualizado com o novo conteúdo, e as traduções serão acionadas novamente.
- Se um arquivo for suportado, mas não corresponder a nenhum arquivo de origem existente, ele será adicionado à lista
not_found_filese ignorado. - Arquivos com formatos não suportados são listados em
unsupported_filese ignorados. - Arquivos com conteúdo inválido também são listados em
unsupported_filese ignorados. - Pacotes grandes podem levar mais tempo para serem processados. Os arquivos são processados um a um para gerenciar recursos, portanto, é melhor dividir envios muito grandes (mais de 100 arquivos) em lotes menores. Todos os arquivos no pacote são configurados para tradução automática.
- O ZIP enviado deve ser válido e legível. Todos os arquivos internos devem estar em um formato suportado. Os nomes dos arquivos não devem incluir caracteres especiais que possam causar problemas de caminho.
- Se um
callback_urlfor fornecido, uma requisiçãoPOSTserá enviada para cada arquivo de origem processado com seus resultados.
Requisição HTTP
POST https://app.ptc.wpml.org/api/v1/source_files/bulkParâmetros
| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
zip_file |
file | Sim | Um arquivo ZIP contendo os arquivos de origem a serem enviados. Ele deve ser um arquivo ZIP válido. |
file_tag_name |
string | Não | O nome da tag de arquivo a ser associada a todos os arquivos de origem no arquivo ZIP. Se não for especificado, a tag de arquivo padrão do projeto será usada. Cada arquivo de origem é identificado de forma exclusiva pela combinação de file_path e file_tag_name. |
callback_url |
string | Não | A URL que recebe notificações de webhook quando cada arquivo é processado. |
Estrutura Esperada do Arquivo ZIP
O arquivo ZIP pode conter arquivos de origem em qualquer estrutura de diretórios. A estrutura de diretórios é preservada, e os arquivos são processados recursivamente.
Exemplo de Estrutura do ZIP:
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 Arquivo Suportados:
- JSON: arquivos
.json - gettext: arquivos
.po,.pot - Properties: arquivos
.properties - YAML: arquivos
.yml,.yaml - XML: arquivos
.xml - Strings: arquivos
.strings - XLIFF: arquivos
.xliff,.xlf - CSV: arquivos
.csv - PHP: arquivos
.php
Respostas
Resposta de Sucesso
{
"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 da Resposta
| Campo | Tipo | Descrição |
|---|---|---|
success |
boolean | Se a operação de envio em lote foi bem-sucedida. |
file_tag |
object | As informações da tag de arquivo. |
file_tag.id |
integer | O identificador da tag de arquivo. |
file_tag.name |
string | O nome da tag de arquivo. |
processed_files |
array[object] | Um array de arquivos de origem que foram processados com sucesso. |
processed_files[].id |
integer | O identificador exclusivo do arquivo de origem criado. |
processed_files[].file_path |
string | O caminho do arquivo de origem, preservando a estrutura original do ZIP. |
processed_files[].created_at |
string | Um timestamp ISO 8601 indicando quando o arquivo de origem foi criado. |
processed_files[].file_tag |
object | As informações da tag de arquivo. |
processed_files[].file_tag.id |
integer | O identificador da tag de arquivo. |
processed_files[].file_tag.name |
string | O nome da tag de arquivo. |
unsupported_files |
array[string] | Um array de nomes de arquivos que não estão em um formato suportado. |
not_found_files |
array[string] | Um array de arquivos suportados que não corresponderam a nenhum arquivo de origem existente e foram ignorados. |
Respostas de Erro
Arquivo ZIP Inválido
{
"success": false,
"error": "File format is invalid",
"processed_files": [],
"unsupported_files": []
}Falha no Processamento
{
"success": false,
"error": "Failed to process ZIP archive",
"processed_files": [],
"unsupported_files": []
}Não Autorizado
{
"error": "Unauthorized access. Please provide a valid API token."
}Proibido
{
"error": "Access denied. Insufficient permissions."
}Callback de Webhook
Quando uma callback_url é fornecida, uma requisição POST é enviada para cada arquivo processado.
Corpo da requisição de callback (por arquivo):
{
"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"
}Exemplos de Requisições
Envio em lote básico:
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"Requisição com 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"Exemplos 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);Próximo:
Encontre os formatos de arquivo suportados e idiomas de destino via API →