Autenticação Visão Geral A API Pontotel utiliza Bearer Token Authentication (JWT) para autenticar requisições.
Fluxo de Autenticação
Enviar credenciais para o endpoint /login/ Receber access_token na resposta Incluir token no header Authorization: Bearer {token} Token expira em 1 hora Endpoint de Login POST /api/v4/login/
Request JSON {
"username" : "seu_usuario" ,
"password" : "sua_senha"
}
Response (200 OK) JSON {
"access_token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." ,
"token_type" : "Bearer" ,
"expires_in" : 3600 ,
"user" : {
"id" : 123 ,
"username" : "seu_usuario" ,
"email" : "seu@email.com"
}
}
Exemplos de Código Python JavaScript cURL
Python import requests
from datetime import datetime , timedelta
class PontotelAuth :
def __init__ ( self , username , password , base_url ):
self . username = username
self . password = password
self . base_url = base_url
self . token = None
self . token_expires_at = None
def login ( self ):
"""Realiza login e obtém token"""
url = f " { self . base_url } /login/"
payload = {
"username" : self . username ,
"password" : self . password
}
response = requests . post ( url , json = payload )
response . raise_for_status ()
data = response . json ()
self . token = data [ "access_token" ]
self . token_expires_at = datetime . now () + timedelta ( seconds = data [ "expires_in" ])
return self . token
def get_token ( self ):
"""Retorna token válido, renovando se necessário"""
if not self . token or datetime . now () >= self . token_expires_at :
self . login ()
return self . token
def get_headers ( self ):
"""Retorna headers com autenticação"""
return {
"Authorization" : f "Bearer { self . get_token () } " ,
"Content-Type" : "application/json"
}
# Uso
auth = PontotelAuth (
username = "seu_usuario" ,
password = "sua_senha" ,
base_url = "https://apis.pontotel.com.br/pontotel/api/v4"
)
# Fazer requisições
headers = auth . get_headers ()
response = requests . get (
"https://apis.pontotel.com.br/pontotel/api/v4/usuarios/" ,
headers = headers
)
JavaScript class PontotelAuth {
constructor ( username , password , baseUrl ) {
this . username = username ;
this . password = password ;
this . baseUrl = baseUrl ;
this . token = null ;
this . tokenExpiresAt = null ;
}
async login () {
const url = ` ${ this . baseUrl } /login/` ;
const response = await fetch ( url , {
method : 'POST' ,
headers : { 'Content-Type' : 'application/json' },
body : JSON . stringify ({
username : this . username ,
password : this . password
})
});
if ( ! response . ok ) {
throw new Error ( `Login failed: ${ response . status } ` );
}
const data = await response . json ();
this . token = data . access_token ;
this . tokenExpiresAt = Date . now () + ( data . expires_in * 1000 );
return this . token ;
}
async getToken () {
if ( ! this . token || Date . now () >= this . tokenExpiresAt ) {
await this . login ();
}
return this . token ;
}
async getHeaders () {
const token = await this . getToken ();
return {
'Authorization' : `Bearer ${ token } ` ,
'Content-Type' : 'application/json'
};
}
}
// Uso
const auth = new PontotelAuth (
'seu_usuario' ,
'sua_senha' ,
'https://apis.pontotel.com.br/pontotel/api/v4'
);
// Fazer requisições
const headers = await auth . getHeaders ();
const response = await fetch (
'https://apis.pontotel.com.br/pontotel/api/v4/usuarios/' ,
{ headers }
);
Bash # 1. Login
curl -X POST "https://apis.pontotel.com.br/pontotel/api/v4/login/" \
-H "Content-Type: application/json" \
-d '{
"username": "seu_usuario",
"password": "sua_senha"
}' \
| jq -r '.access_token' > token.txt
# 2. Usar token
TOKEN = $( cat token.txt)
curl -X GET "https://apis.pontotel.com.br/pontotel/api/v4/usuarios/" \
-H "Authorization: Bearer $TOKEN "
Segurança Práticas Importantes
Nunca compartilhe credenciais ou tokens Armazene tokens em variáveis de ambiente ou secret managers Rotacione credenciais regularmente Use HTTPS sempre (obrigatório) Não faça commit de tokens no Git Armazenamento Seguro Expiração e Renovação Tokens expiram em 1 hora (3600 segundos) Implemente lógica de renovação automática Trate erros 401 Unauthorized reaautenticando Exemplo de Retry Logic Python import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def requests_retry_session ( retries = 3 ):
session = requests . Session ()
retry = Retry (
total = retries ,
read = retries ,
connect = retries ,
backoff_factor = 0.3 ,
status_forcelist = ( 401 , 500 , 502 , 504 ),
)
adapter = HTTPAdapter ( max_retries = retry )
session . mount ( 'http://' , adapter )
session . mount ( 'https://' , adapter )
return session
# Uso
session = requests_retry_session ()
response = session . get ( url , headers = headers )
Erros Comuns Código Erro Solução 400 Bad Request Verificar formato do payload 401 Unauthorized Credenciais inválidas ou token expirado 403 Forbidden Sem permissão para o recurso 429 Too Many Requests Aguardar rate limit
Próximos Passos