sharpfy-nextapi 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ """SDK oficial da NextAPI para Python (CNPJ, CEP, sócios, mercado). Sem dependências."""
2
+ from sharpfy_nextapi._validation import normalize_cep, normalize_cnpj
3
+ from sharpfy_nextapi._version import VERSION as __version__
4
+ from sharpfy_nextapi.client import NextApi, NextApiClient
5
+ from sharpfy_nextapi.errors import (ErrorCodes, NextApiAuthenticationError, NextApiConnectionError, NextApiError,
6
+ NextApiInsufficientCreditsError, NextApiNotFoundError,
7
+ NextApiPaidPlanRequiredError, NextApiRateLimitError, NextApiServerError,
8
+ NextApiValidationError)
9
+
10
+ __all__ = [
11
+ "NextApiClient", "NextApi", "ErrorCodes", "NextApiError", "NextApiAuthenticationError",
12
+ "NextApiInsufficientCreditsError", "NextApiPaidPlanRequiredError", "NextApiNotFoundError",
13
+ "NextApiValidationError", "NextApiRateLimitError", "NextApiServerError", "NextApiConnectionError",
14
+ "normalize_cnpj", "normalize_cep", "__version__",
15
+ ]
@@ -0,0 +1,40 @@
1
+ """Transporte HTTP sobre a biblioteca padrão (urllib), sem dependências."""
2
+ import ssl
3
+ import urllib.error
4
+ import urllib.request
5
+ from typing import Dict, Mapping, NamedTuple, Optional, Protocol
6
+
7
+
8
+ class Response(NamedTuple):
9
+ status: int
10
+ headers: Mapping[str, str]
11
+ body: bytes
12
+
13
+
14
+ class Transport(Protocol):
15
+ """Faz uma requisição e devolve a resposta, seja qual for o status. Erros de rede viram exceção (OSError)."""
16
+
17
+ def __call__(self, method: str, url: str, headers: Dict[str, str], body: Optional[bytes],
18
+ timeout: float) -> Response: ...
19
+
20
+
21
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
22
+ # urllib manda o cabeçalho Authorization junto para o destino do redirecionamento: não seguir.
23
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
24
+ return None
25
+
26
+
27
+ class UrllibTransport:
28
+ def __init__(self, ssl_context: Optional[ssl.SSLContext] = None):
29
+ context = ssl_context or ssl.create_default_context()
30
+ self._opener = urllib.request.build_opener(_NoRedirect(), urllib.request.HTTPSHandler(context=context))
31
+
32
+ def __call__(self, method, url, headers, body, timeout):
33
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
34
+ try:
35
+ with self._opener.open(request, timeout=timeout) as response:
36
+ return Response(response.status, {k.lower(): v for k, v in response.headers.items()}, response.read())
37
+ except urllib.error.HTTPError as error: # status >= 400 e redirecionamentos não seguidos
38
+ with error:
39
+ payload = error.read()
40
+ return Response(error.code, {k.lower(): v for k, v in (error.headers or {}).items()}, payload)
@@ -0,0 +1,94 @@
1
+ """Normalização e validação das entradas, antes de qualquer requisição."""
2
+ import math
3
+ import re
4
+ from datetime import date
5
+ from typing import Any, Dict, Iterable, List, Optional
6
+ from urllib.parse import quote, urlencode
7
+
8
+ from sharpfy_nextapi.errors import NextApiValidationError
9
+
10
+ _CNPJ = re.compile(r"^[0-9A-Z]{12}[0-9]{2}$")
11
+ _CEP = re.compile(r"^[0-9]{8}$")
12
+ _HASH = re.compile(r"^[0-9a-fA-F]{20}$")
13
+ _SEGMENT = re.compile(r"^[0-9A-Za-z_-]+$")
14
+ _STRIP_CNPJ = re.compile(r"[\s./-]")
15
+
16
+
17
+ def _invalid(message: str):
18
+ raise NextApiValidationError(message)
19
+
20
+
21
+ def normalize_cnpj(cnpj: str) -> str:
22
+ """Tira pontuação e põe em maiúsculas. Aceita o CNPJ alfanumérico (12 alfanuméricos e 2 dígitos)."""
23
+ value = _STRIP_CNPJ.sub("", str(cnpj or "")).upper()
24
+ if not _CNPJ.match(value):
25
+ _invalid(f'CNPJ inválido: "{cnpj}". Informe 14 caracteres, com ou sem pontuação.')
26
+ return value
27
+
28
+
29
+ def normalize_cep(cep: str) -> str:
30
+ value = re.sub(r"[\s.-]", "", str(cep or ""))
31
+ if not _CEP.match(value):
32
+ _invalid(f'CEP inválido: "{cep}". Informe 8 dígitos.')
33
+ return value
34
+
35
+
36
+ def normalize_hash_socio(value: str) -> str:
37
+ text = str(value or "").strip()
38
+ if not _HASH.match(text):
39
+ _invalid("hash_socio inválido: são 20 caracteres hexadecimais.")
40
+ return text.lower()
41
+
42
+
43
+ def path_segment(value: Any, name: str) -> str:
44
+ text = str(value if value is not None else "").strip()
45
+ if not _SEGMENT.match(text):
46
+ _invalid(f'{name} inválido: "{value}".')
47
+ return quote(text, safe="")
48
+
49
+
50
+ def positive_int(value: Any, name: str) -> str:
51
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
52
+ _invalid(f'{name} inválido: "{value}".')
53
+ return str(value)
54
+
55
+
56
+ def require_positive(value: Any, name: str) -> None:
57
+ if not _number(value) or value <= 0:
58
+ _invalid(f"{name} tem de ser maior que zero.")
59
+
60
+
61
+ def require_range(value: Any, low: float, high: float, name: str) -> None:
62
+ if not _number(value) or not low <= value <= high:
63
+ _invalid(f"{name} tem de estar entre {low:g} e {high:g}.")
64
+
65
+
66
+ def batch(cnpjs: Iterable[str]) -> List[str]:
67
+ if isinstance(cnpjs, (str, bytes)):
68
+ _invalid("Informe uma lista de CNPJs, não um texto.")
69
+ values = list(cnpjs or [])
70
+ if not values:
71
+ _invalid("Informe ao menos um CNPJ.")
72
+ if len(values) > 100:
73
+ _invalid(f"O lote aceita até 100 CNPJs; vieram {len(values)}.")
74
+ return [normalize_cnpj(c) for c in values]
75
+
76
+
77
+ def query(params: Dict[str, Any]) -> str:
78
+ """Query string sem os valores ausentes, na ordem informada; booleanos como true/false."""
79
+ pairs = []
80
+ for key, value in params.items():
81
+ if value is None or value == "":
82
+ continue
83
+ if isinstance(value, bool):
84
+ value = "true" if value else "false"
85
+ elif isinstance(value, date):
86
+ value = value.isoformat()[:10]
87
+ elif isinstance(value, float) and value.is_integer():
88
+ value = int(value)
89
+ pairs.append((key, str(value)))
90
+ return "?" + urlencode(pairs) if pairs else ""
91
+
92
+
93
+ def _number(value: Any) -> bool:
94
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
@@ -0,0 +1 @@
1
+ VERSION = "0.2.0"
@@ -0,0 +1,170 @@
1
+ """Cliente da NextAPI."""
2
+ import json
3
+ import os
4
+ import platform
5
+ import sys
6
+ import re
7
+ import random
8
+ import time
9
+ from email.utils import parsedate_to_datetime
10
+ from typing import Any, Optional
11
+ from urllib.parse import urlsplit
12
+
13
+ from sharpfy_nextapi import _version
14
+ from sharpfy_nextapi._transport import Transport, UrllibTransport
15
+ from sharpfy_nextapi.errors import NextApiAuthenticationError, NextApiConnectionError, error_class
16
+ from sharpfy_nextapi.resources.ceps import Ceps
17
+ from sharpfy_nextapi.resources.cnpj import Cnpj
18
+ from sharpfy_nextapi.resources.creditos import Creditos
19
+ from sharpfy_nextapi.resources.empresas import Empresas
20
+ from sharpfy_nextapi.resources.localidades import Cnaes, Estados, Municipios
21
+ from sharpfy_nextapi.resources.mercado import Mercado
22
+ from sharpfy_nextapi.resources.socios import Socios
23
+
24
+ DEFAULT_BASE_URL = "https://api.nextapi.com.br"
25
+ _RETRYABLE = {429, 502, 503, 504}
26
+ _LOCAL = {"localhost", "127.0.0.1", "::1"}
27
+
28
+
29
+ class NextApiClient:
30
+ """Cliente da NextAPI. Sem dependências: só a biblioteca padrão.
31
+
32
+ >>> nextapi = NextApiClient() # lê NEXTAPI_KEY
33
+ >>> empresa = nextapi.cnpj.consultar("11.222.333/0001-81")
34
+
35
+ :param api_key: ``nxa_live_…`` (produção) ou ``nxa_test_…`` (sandbox). Padrão: ``NEXTAPI_KEY``.
36
+ :param base_url: padrão ``https://api.nextapi.com.br``; só https (http apenas para localhost).
37
+ :param timeout: segundos por tentativa (padrão 30).
38
+ :param max_retries: novas tentativas em falha transitória (429, 502, 503, 504, rede), só em leituras.
39
+ :param app_info: complemento do User-Agent para identificar a sua aplicação (ex.: ``"minha-app/1.2"``).
40
+ :param transport: transporte HTTP alternativo (testes, proxies corporativos).
41
+ """
42
+
43
+ def __init__(self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0,
44
+ max_retries: int = 2, app_info: Optional[str] = None, transport: Optional[Transport] = None):
45
+ key = (api_key if api_key is not None else os.environ.get("NEXTAPI_KEY", "")).strip()
46
+ if not key:
47
+ raise NextApiAuthenticationError("Chave de API não informada: passe api_key ou defina NEXTAPI_KEY.")
48
+ self.__api_key = key
49
+ self.environment = "sandbox" if key.startswith("nxa_test_") else "production"
50
+ self.base_url = _check_base_url(base_url)
51
+ self.timeout = timeout
52
+ self.max_retries = max(0, int(max_retries))
53
+ self._transport = transport or UrllibTransport()
54
+ app = sanitize_app_info(app_info)
55
+ runtime = f"python/{platform.python_version()}"
56
+ ua = f"nextapi-python/{_version.VERSION} {runtime}"
57
+ self._user_agent = f"{ua} {app}" if app else ua
58
+ self._client_info = f"{runtime}; {_os_name(sys.platform)}" + (f"; {app}" if app else "")
59
+
60
+ self.cnpj = Cnpj(self)
61
+ self.socios = Socios(self)
62
+ self.ceps = Ceps(self)
63
+ self.empresas = Empresas(self)
64
+ self.cnaes = Cnaes(self)
65
+ self.estados = Estados(self)
66
+ self.municipios = Municipios(self)
67
+ self.mercado = Mercado(self)
68
+ self.creditos = Creditos(self)
69
+
70
+ def __repr__(self) -> str: # nunca mostra a chave
71
+ return f"NextApiClient(base_url={self.base_url!r}, environment={self.environment!r})"
72
+
73
+ def _request(self, method: str, path: str, body: Any = None) -> Any:
74
+ url = self.base_url + path
75
+ headers = {
76
+ "Authorization": f"Bearer {self.__api_key}",
77
+ "Accept": "application/json",
78
+ "User-Agent": self._user_agent,
79
+ "X-NextApi-Client": f"python/{_version.VERSION}",
80
+ "X-NextApi-Client-Info": self._client_info,
81
+ }
82
+ payload = None
83
+ if body is not None:
84
+ headers["Content-Type"] = "application/json"
85
+ payload = json.dumps(body).encode("utf-8")
86
+ # POST de lote consome créditos: nunca repete sozinho.
87
+ retries = self.max_retries if method == "GET" else 0
88
+
89
+ attempt = 0
90
+ while True:
91
+ try:
92
+ response = self._transport(method, url, headers, payload, self.timeout)
93
+ except OSError as error: # URLError, timeout, conexão recusada, TLS
94
+ if attempt < retries:
95
+ attempt += 1
96
+ time.sleep(_backoff(attempt))
97
+ continue
98
+ reason = getattr(error, "reason", error)
99
+ raise NextApiConnectionError(f"Falha de conexão com a NextAPI: {reason}", body=error) from None
100
+
101
+ if 200 <= response.status < 300:
102
+ return json.loads(response.body) if response.body else None
103
+ if 300 <= response.status < 400:
104
+ raise NextApiConnectionError(
105
+ f"A NextAPI respondeu com redirecionamento ({response.status}); o SDK não o segue para não "
106
+ "reenviar a chave.", status=response.status)
107
+
108
+ wait = _retry_after(response.headers.get("retry-after"))
109
+ if response.status in _RETRYABLE and attempt < retries:
110
+ attempt += 1
111
+ time.sleep(wait if wait is not None else _backoff(attempt))
112
+ continue
113
+ raise _to_error(response, wait)
114
+
115
+
116
+ def _to_error(response, wait):
117
+ text = response.body.decode("utf-8", errors="replace")
118
+ try:
119
+ body = json.loads(text) if text else None
120
+ except ValueError:
121
+ body = text
122
+ fields = body if isinstance(body, dict) else {}
123
+ code = fields.get("code") if isinstance(fields.get("code"), int) else None
124
+ message = fields.get("message") if isinstance(fields.get("message"), str) and fields.get("message") else None
125
+ cls = error_class(response.status, code)
126
+ return cls(message or f"HTTP {response.status}", status=response.status, code=code, body=body,
127
+ request_id=response.headers.get("x-request-id"), retry_after=wait)
128
+
129
+
130
+ def _check_base_url(raw: str) -> str:
131
+ parts = urlsplit(raw)
132
+ if not parts.scheme or not parts.hostname:
133
+ raise ValueError(f"base_url inválida: {raw}")
134
+ if parts.scheme != "https" and not (parts.scheme == "http" and parts.hostname in _LOCAL):
135
+ raise ValueError("base_url tem de usar https (http só para localhost): a chave vai no cabeçalho.")
136
+ return f"{parts.scheme}://{parts.netloc}{parts.path.rstrip('/')}"
137
+
138
+
139
+ def _backoff(attempt: int) -> float:
140
+ base = min(8.0, 0.5 * 2 ** (attempt - 1))
141
+ return base / 2 + random.random() * base / 2
142
+
143
+
144
+ def _retry_after(header: Optional[str]) -> Optional[float]:
145
+ if not header:
146
+ return None
147
+ try:
148
+ seconds = float(header)
149
+ except ValueError:
150
+ try:
151
+ seconds = parsedate_to_datetime(header).timestamp() - time.time()
152
+ except (TypeError, ValueError):
153
+ return None
154
+ return min(max(seconds, 0.0), 60.0)
155
+
156
+
157
+ NextApi = NextApiClient
158
+
159
+
160
+ def sanitize_app_info(info):
161
+ """Só caracteres seguros num cabeçalho: CR/LF ou espaço no app_info quebrariam a requisição."""
162
+ return re.sub(r"[^A-Za-z0-9._/@+-]", "", info or "")[:64]
163
+
164
+
165
+ def _os_name(name):
166
+ if name.startswith("win"):
167
+ return "windows"
168
+ if name.startswith("linux"):
169
+ return "linux"
170
+ return "darwin" if name == "darwin" else "other"
@@ -0,0 +1,103 @@
1
+ """Erros do SDK. Toda falha da API vira um :class:`NextApiError`; a subclasse diz o que fazer.
2
+
3
+ O código numérico da API (``code``) distingue casos com o mesmo status HTTP: 405 vale tanto para
4
+ "sem créditos" (1004, 1006) quanto para "plano pago obrigatório" (1012, 1005).
5
+ """
6
+ from typing import Any, Optional
7
+
8
+
9
+ class ErrorCodes:
10
+ NOT_FOUND = 1000
11
+ TOKEN_NOT_PROVIDED = 1001
12
+ TOKEN_INVALID = 1002
13
+ TOO_MANY_REQUESTS = 1003
14
+ MISSING_CREDITS = 1004
15
+ LIVE_SEARCH_NOT_ALLOWED = 1005
16
+ LIVE_SEARCH_MISSING_CREDITS = 1006
17
+ INVALID_CEP = 1007
18
+ REQUIRES_PAID_PLAN = 1012
19
+ EXTERNAL_PROVIDER_FAILURE = 1014
20
+ SANDBOX_DAILY_LIMIT = 1015
21
+ SANDBOX_DISABLED = 1016
22
+
23
+
24
+ class NextApiError(Exception):
25
+ """Falha numa chamada à NextAPI.
26
+
27
+ :ivar status: status HTTP (0 quando a requisição nem chegou à API).
28
+ :ivar code: código de erro da NextAPI (ver :class:`ErrorCodes`), quando informado.
29
+ :ivar body: corpo da resposta de erro (JSON interpretado, ou o texto).
30
+ :ivar request_id: cabeçalho ``x-request-id``, para o suporte.
31
+ """
32
+
33
+ def __init__(self, message: str, status: int = 0, code: Optional[int] = None, body: Any = None,
34
+ request_id: Optional[str] = None, retry_after: Optional[float] = None):
35
+ super().__init__(message)
36
+ self.message = message
37
+ self.status = status
38
+ self.code = code
39
+ self.body = body
40
+ self.request_id = request_id
41
+ self.retry_after = retry_after
42
+
43
+ def __repr__(self) -> str:
44
+ return f"{type(self).__name__}(status={self.status}, code={self.code}, message={self.message!r})"
45
+
46
+
47
+ class NextApiAuthenticationError(NextApiError):
48
+ """Chave ausente, inválida ou revogada."""
49
+
50
+
51
+ class NextApiInsufficientCreditsError(NextApiError):
52
+ """Sem créditos para a consulta (1004, 1006)."""
53
+
54
+
55
+ class NextApiPaidPlanRequiredError(NextApiError):
56
+ """O recurso exige plano pago ou créditos avulsos (1012, 1005)."""
57
+
58
+
59
+ class NextApiNotFoundError(NextApiError):
60
+ """O CNPJ, CEP ou sócio pesquisado não existe (404)."""
61
+
62
+
63
+ class NextApiValidationError(NextApiError, ValueError):
64
+ """Parâmetro rejeitado pela API (400) ou pelo próprio SDK antes de enviar (status 0)."""
65
+
66
+
67
+ class NextApiRateLimitError(NextApiError):
68
+ """Limite de requisições do plano ou do sandbox (429). ``retry_after`` em segundos."""
69
+
70
+
71
+ class NextApiServerError(NextApiError):
72
+ """Falha do lado da API (5xx), inclusive a do provedor em tempo real (1014)."""
73
+
74
+
75
+ class NextApiConnectionError(NextApiError):
76
+ """Não houve resposta: rede, DNS, TLS, tempo esgotado ou redirecionamento recusado."""
77
+
78
+
79
+ _BY_CODE = {
80
+ ErrorCodes.TOKEN_NOT_PROVIDED: NextApiAuthenticationError,
81
+ ErrorCodes.TOKEN_INVALID: NextApiAuthenticationError,
82
+ ErrorCodes.SANDBOX_DISABLED: NextApiAuthenticationError,
83
+ ErrorCodes.MISSING_CREDITS: NextApiInsufficientCreditsError,
84
+ ErrorCodes.LIVE_SEARCH_MISSING_CREDITS: NextApiInsufficientCreditsError,
85
+ ErrorCodes.REQUIRES_PAID_PLAN: NextApiPaidPlanRequiredError,
86
+ ErrorCodes.LIVE_SEARCH_NOT_ALLOWED: NextApiPaidPlanRequiredError,
87
+ }
88
+
89
+
90
+ def error_class(status: int, code: Optional[int]) -> type:
91
+ if code in _BY_CODE:
92
+ return _BY_CODE[code]
93
+ if status in (401, 403):
94
+ return NextApiAuthenticationError
95
+ if status == 404:
96
+ return NextApiNotFoundError
97
+ if status == 429:
98
+ return NextApiRateLimitError
99
+ if status >= 500:
100
+ return NextApiServerError
101
+ if status in (400, 422):
102
+ return NextApiValidationError
103
+ return NextApiError