Upsert
curl --request PUT \
--url http://api.gu1.ai/entities/upsert \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": true
}
'import requests
url = "http://api.gu1.ai/entities/upsert"
payload = {
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.put(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'PUT',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
entity: {},
options: {},
'options.conflictResolution': {},
'options.deduplicationStrategy': {},
'options.createRelationships': true
})
};
fetch('http://api.gu1.ai/entities/upsert', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/entities/upsert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode([
'entity' => [
],
'options' => [
],
'options.conflictResolution' => [
],
'options.deduplicationStrategy' => [
],
'options.createRelationships' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/entities/upsert"
payload := strings.NewReader("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.put("http://api.gu1.ai/entities/upsert")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/entities/upsert")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Put.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}"
response = http.request(request)
puts response.read_body{
"success": true,
"action": "<string>",
"entity": {},
"previousEntity": {},
"confidence": 123,
"reasoning": "<string>",
"conflicts": [
{}
]
}Referência API
Upsert de uma entidade empresa
Cria ou atualiza uma empresa no gu1 com detecção de duplicatas que verifica ID externo, identificação fiscal e razão social para evitar colisões.
PUT
/
entities
/
upsert
Upsert
curl --request PUT \
--url http://api.gu1.ai/entities/upsert \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": true
}
'import requests
url = "http://api.gu1.ai/entities/upsert"
payload = {
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.put(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'PUT',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
entity: {},
options: {},
'options.conflictResolution': {},
'options.deduplicationStrategy': {},
'options.createRelationships': true
})
};
fetch('http://api.gu1.ai/entities/upsert', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/entities/upsert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode([
'entity' => [
],
'options' => [
],
'options.conflictResolution' => [
],
'options.deduplicationStrategy' => [
],
'options.createRelationships' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/entities/upsert"
payload := strings.NewReader("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.put("http://api.gu1.ai/entities/upsert")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/entities/upsert")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Put.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}"
response = http.request(request)
puts response.read_body{
"success": true,
"action": "<string>",
"entity": {},
"previousEntity": {},
"confidence": 123,
"reasoning": "<string>",
"conflicts": [
{}
]
}Visão Geral
O endpoint upsert cria inteligentemente uma nova empresa ou atualiza uma existente com base em estratégias de detecção de duplicatas configuráveis. Ele lida automaticamente com conflitos e previne registros duplicados usando correspondência exata, correspondência difusa ou detecção de similaridade alimentada por IA.Endpoint
PUT http://api.gu1.ai/entities/upsert
Autenticação
Requer uma chave de API válida no cabeçalho Authorization:Authorization: Bearer YOUR_API_KEY
Corpo da Requisição
object
required
Os dados da empresa (mesma estrutura do endpoint Criar Empresa)
object
Opções de configuração para comportamento do upsert
enum
Como lidar com conflitos quando uma empresa existente é encontrada:
source_wins- Novos dados sobrescrevem dados existentestarget_wins- Manter dados existentes, ignorar novos dadosmanual_review- Sinalizar para revisão manual sem atualizarsmart_merge(padrão) - Mesclar inteligentemente ambos os conjuntos de dados
enum
Estratégia para detectar empresas duplicadas:
exact_match- Correspondência por externalId e taxId (case-insensitive)fuzzy_match- Correspondência de similaridade em name e taxId (limite de 80%)ai_similarity- Detecção de similaridade semântica alimentada por IAhybrid(recomendado) - Correspondência exata com fallback difuso
boolean
default:"true"
Se deve criar automaticamente relacionamentos entre entidades
Resposta
boolean
Indica se a operação foi bem-sucedida
string
A ação realizada:
created ou updatedobject
O estado final da empresa após o upsert
object
O estado da empresa antes da atualização (null se recém-criada)
number
Pontuação de confiança (0-1) para a correspondência de detecção de duplicatas
string
Explicação de por que a empresa foi criada/atualizada
array
Array de conflitos em nível de campo detectados durante a mesclagem (se houver)
Exemplos
Upsert Simples (Comportamento Padrão)
curl -X PUT http://api.gu1.ai/entities/upsert \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entity": {
"type": "company",
"externalId": "business_12345",
"name": "María González",
"countryCode": "AR",
"taxId": "20-12345678-9",
"entityData": {
"company": {
"firstName": "María",
"lastName": "González",
"dateOfBirth": "1985-03-15",
"occupation": "Software Engineer",
"income": 85000
}
}
}
}'
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'company',
externalId: 'business_12345',
name: 'María González',
countryCode: 'AR',
taxId: '20-12345678-9',
entityData: {
company: {
firstName: 'María',
lastName: 'González',
dateOfBirth: '1985-03-15',
occupation: 'Software Engineer',
income: 85000
}
}
}
})
});
const result = await response.json();
console.log(`Action: ${result.action}`); // 'created' ou 'updated'
console.log(`Confidence: ${result.confidence}`);
import requests
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'company',
'externalId': 'business_12345',
'name': 'María González',
'countryCode': 'AR',
'taxId': '20-12345678-9',
'entityData': {
'company': {
'firstName': 'María',
'lastName': 'González',
'dateOfBirth': '1985-03-15',
'occupation': 'Software Engineer',
'income': 85000
}
}
}
}
)
result = response.json()
print(f"Action: {result['action']}")
print(f"Confidence: {result['confidence']}")
Upsert com Correspondência Difusa
curl -X PUT http://api.gu1.ai/entities/upsert \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entity": {
"type": "company",
"externalId": "business_new_123",
"name": "Maria Gonzales",
"countryCode": "AR",
"taxId": "20-12345678-9",
"entityData": {
"company": {
"firstName": "Maria",
"lastName": "Gonzales"
}
}
},
"options": {
"deduplicationStrategy": "fuzzy_match",
"conflictResolution": "smart_merge"
}
}'
// Irá corresponder "Maria Gonzales" com "María González" existente
// devido ao limite de similaridade de 80%+
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'company',
externalId: 'business_new_123',
name: 'Maria Gonzales', // Pequena variação na ortografia
countryCode: 'AR',
taxId: '20-12345678-9',
entityData: {
company: {
firstName: 'Maria',
lastName: 'Gonzales'
}
}
},
options: {
deduplicationStrategy: 'fuzzy_match',
conflictResolution: 'smart_merge'
}
})
});
const result = await response.json();
console.log(`Matched with confidence: ${result.confidence}`);
console.log(`Reasoning: ${result.reasoning}`);
import requests
# Irá corresponder "Maria Gonzales" com "María González" existente
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'company',
'externalId': 'business_new_123',
'name': 'Maria Gonzales', # Pequena variação
'countryCode': 'AR',
'taxId': '20-12345678-9',
'entityData': {
'company': {
'firstName': 'Maria',
'lastName': 'Gonzales'
}
}
},
'options': {
'deduplicationStrategy': 'fuzzy_match',
'conflictResolution': 'smart_merge'
}
}
)
result = response.json()
print(f"Matched with confidence: {result['confidence']}")
print(f"Reasoning: {result['reasoning']}")
Exemplos de Resposta
Nova Empresa Criada
{
"success": true,
"action": "created",
"entity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"externalId": "business_12345",
"type": "company",
"name": "María González",
...
},
"previousEntity": null,
"confidence": 1.0,
"reasoning": "No existing entity found matching criteria. Created new entity.",
"conflicts": []
}
Empresa Existente Atualizada
{
"success": true,
"action": "updated",
"entity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"externalId": "business_12345",
"type": "company",
"name": "María González",
"entityData": {
"company": {
"income": 95000
}
},
...
},
"previousEntity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"entityData": {
"company": {
"income": 85000
}
},
...
},
"confidence": 1.0,
"reasoning": "Exact match found on externalId. Updated existing entity with smart merge.",
"conflicts": [
{
"field": "entityData.company.income",
"oldValue": 85000,
"newValue": 95000,
"resolution": "source_wins"
}
]
}
Casos de Uso
Importação de Dados do CRM
// Importar dados de empresa do CRM, evitando duplicatas
async function importBusiness(crmData) {
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'company',
externalId: crmData.businessId,
name: crmData.fullName,
countryCode: crmData.country,
taxId: crmData.taxId,
entityData: {
company: {
firstName: crmData.firstName,
lastName: crmData.lastName,
income: crmData.annualIncome
}
},
attributes: {
source: 'crm_import',
importDate: new Date().toISOString()
}
},
options: {
deduplicationStrategy: 'hybrid',
conflictResolution: 'smart_merge'
}
})
});
return response.json();
}
Enriquecimento Progressivo de Dados
def enrich_company_data(external_id, new_data):
"""Adicionar progressivamente dados à empresa conforme ficam disponíveis"""
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'company',
'externalId': external_id,
'name': new_data.get('name'),
'countryCode': new_data.get('country'),
'entityData': new_data.get('details', {}),
'attributes': new_data.get('attributes', {})
},
'options': {
'deduplicationStrategy': 'exact_match',
'conflictResolution': 'smart_merge' # Mesclar novo com existente
}
}
)
result = response.json()
if result['action'] == 'updated':
print(f"Enriched existing company with new data")
return result
Melhores Práticas
-
Escolha a Estratégia Certa:
exact_matchpara dados limpos e estruturados com IDs confiáveisfuzzy_matchpara dados inseridos por usuários com possíveis erros de digitaçãohybridpara a maioria dos cenários de produção
-
Lide com Conflitos Graciosamente:
- Use
smart_mergepara resolução automática - Use
manual_reviewpara dados críticos - Verifique o array
conflictsna resposta para mudanças importantes
- Use
-
Monitore Pontuações de Confiança:
- Pontuações abaixo de 0.7 podem indicar correspondências fracas
- Registre atualizações de baixa confiança para revisão
Respostas de Erro
400 Bad Request
{
"error": "Invalid tax ID format for country"
}
500 Internal Server Error
{
"error": "Failed to upsert entity"
}
Próximos Passos
- Listar Empresas - Consultar empresas com upsert
- Atualizar Empresa - Fazer atualizações direcionadas
- Obter Empresa - Recuperar detalhes completos da empresa
Was this page helpful?