apizen-sdk 0.1.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.
- apizen/__init__.py +12 -0
- apizen/client.py +69 -0
- apizen/cnpj.py +45 -0
- apizen/py.typed +0 -0
- apizen_sdk-0.1.0.dist-info/METADATA +49 -0
- apizen_sdk-0.1.0.dist-info/RECORD +8 -0
- apizen_sdk-0.1.0.dist-info/WHEEL +4 -0
- apizen_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
apizen/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""SDK oficial das APIs da Apizen: CNPJ e CEP. Só a biblioteca padrão; Python 3.10+.
|
|
2
|
+
|
|
3
|
+
from apizen import Apizen
|
|
4
|
+
apizen = Apizen(cnpj_key="sk_cnpj_…")
|
|
5
|
+
empresa = apizen.cnpj("33.000.167/0001-01") # None when there is none
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .client import Apizen, ApizenError
|
|
9
|
+
from .cnpj import clean_cnpj, is_valid_cnpj, mask_cnpj
|
|
10
|
+
|
|
11
|
+
__all__ = ["Apizen", "ApizenError", "clean_cnpj", "is_valid_cnpj", "mask_cnpj"]
|
|
12
|
+
__version__ = "0.1.0"
|
apizen/client.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""The Apizen APIs over HTTPS. Secret keys: use this on a server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Dict, Optional
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
CNPJ_URL = "https://cnpj.apizen.com.br"
|
|
13
|
+
CEP_URL = "https://ceps.apizen.com.br"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ApizenError(Exception):
|
|
17
|
+
"""An answer other than 200 or 404: 400 (bad input), 401 (the key), 5xx."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, status: int, message: str):
|
|
20
|
+
super().__init__(message)
|
|
21
|
+
self.status = status
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Apizen:
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
cnpj_key: Optional[str] = None,
|
|
28
|
+
cep_key: Optional[str] = None,
|
|
29
|
+
timeout: float = 15.0,
|
|
30
|
+
cnpj_url: str = CNPJ_URL,
|
|
31
|
+
cep_url: str = CEP_URL,
|
|
32
|
+
):
|
|
33
|
+
self.cnpj_key, self.cep_key, self.timeout = cnpj_key, cep_key, timeout
|
|
34
|
+
self.cnpj_url, self.cep_url = cnpj_url.rstrip("/"), cep_url.rstrip("/")
|
|
35
|
+
|
|
36
|
+
def cnpj(self, cnpj: str) -> Optional[Dict[str, Any]]:
|
|
37
|
+
"""An establishment's record, or None when the CNPJ is not in the Receita's data."""
|
|
38
|
+
return self._get(self.cnpj_url, self.cnpj_key, "cnpj_key", f"/v1/cnpj/{self._cnpj(cnpj)}")
|
|
39
|
+
|
|
40
|
+
def cnpj_nome(self, cnpj: str) -> Optional[Dict[str, Any]]:
|
|
41
|
+
"""Only the company's names: lighter, to check whose a CNPJ is."""
|
|
42
|
+
return self._get(self.cnpj_url, self.cnpj_key, "cnpj_key", f"/v1/cnpj/{self._cnpj(cnpj)}/nome")
|
|
43
|
+
|
|
44
|
+
def cep(self, cep: str) -> Optional[Dict[str, Any]]:
|
|
45
|
+
"""A CEP's address, with the town's IBGE code and a point; None when there is none."""
|
|
46
|
+
digits = quote(re.sub(r"\D", "", cep))
|
|
47
|
+
return self._get(self.cep_url, self.cep_key, "cep_key", f"/v1/cep/{digits}")
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def _cnpj(cnpj: str) -> str:
|
|
51
|
+
return quote(re.sub(r"[./\s-]", "", cnpj).upper())
|
|
52
|
+
|
|
53
|
+
def _get(self, base: str, key: Optional[str], name: str, path: str) -> Optional[Dict[str, Any]]:
|
|
54
|
+
if not key:
|
|
55
|
+
raise ApizenError(401, f"Apizen: set {name}")
|
|
56
|
+
req = urllib.request.Request(
|
|
57
|
+
base + path, headers={"Authorization": f"Bearer {key}", "Accept": "application/json"}
|
|
58
|
+
)
|
|
59
|
+
try:
|
|
60
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
61
|
+
return json.loads(res.read().decode("utf-8"))
|
|
62
|
+
except urllib.error.HTTPError as e:
|
|
63
|
+
if e.code == 404:
|
|
64
|
+
return None
|
|
65
|
+
try:
|
|
66
|
+
message = json.loads(e.read().decode("utf-8")).get("error", f"HTTP {e.code}")
|
|
67
|
+
except (ValueError, AttributeError):
|
|
68
|
+
message = f"HTTP {e.code}"
|
|
69
|
+
raise ApizenError(e.code, message) from None
|
apizen/cnpj.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""CNPJ helpers that need no network: numeric and alphanumeric (letters in the first twelve
|
|
2
|
+
characters since July 2026; a character counts as its ASCII code minus 48)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
_FULL = re.compile(r"^[0-9A-Z]{12}[0-9]{2}$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def clean_cnpj(value: str) -> str:
|
|
12
|
+
"""Upper-cases and keeps what a CNPJ may hold: A-Z only in the first 12 places."""
|
|
13
|
+
out = []
|
|
14
|
+
for c in value.upper():
|
|
15
|
+
if len(out) >= 14:
|
|
16
|
+
break
|
|
17
|
+
if c.isdigit() and c.isascii() or ("A" <= c <= "Z" and len(out) < 12):
|
|
18
|
+
out.append(c)
|
|
19
|
+
return "".join(out)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def mask_cnpj(value: str) -> str:
|
|
23
|
+
"""00.000.000/0000-00, as far as the value goes."""
|
|
24
|
+
v = clean_cnpj(value)
|
|
25
|
+
parts = [(0, 2, ""), (2, 5, "."), (5, 8, "."), (8, 12, "/"), (12, 14, "-")]
|
|
26
|
+
return "".join(sep + v[a:b] for a, b, sep in parts if len(v) > a).lstrip("./-")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _check_digit(body: str) -> int:
|
|
30
|
+
total, weight = 0, 2
|
|
31
|
+
for c in reversed(body):
|
|
32
|
+
total += (ord(c) - 48) * weight
|
|
33
|
+
weight = 2 if weight == 9 else weight + 1
|
|
34
|
+
r = total % 11
|
|
35
|
+
return 0 if r < 2 else 11 - r
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_valid_cnpj(value: str) -> bool:
|
|
39
|
+
"""Whether the check digits are right (not whether the company exists: ask the API)."""
|
|
40
|
+
v = clean_cnpj(value)
|
|
41
|
+
if not _FULL.match(v) or len(set(v)) == 1:
|
|
42
|
+
return False
|
|
43
|
+
d1 = _check_digit(v[:12])
|
|
44
|
+
d2 = _check_digit(v[:12] + str(d1))
|
|
45
|
+
return v[12:] == f"{d1}{d2}"
|
apizen/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: apizen-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SDK oficial das APIs da Apizen: CNPJ (Receita Federal) e CEP (com código IBGE e coordenadas).
|
|
5
|
+
Project-URL: Homepage, https://www.apizen.com.br/docs/sdks
|
|
6
|
+
Project-URL: Source, https://github.com/apizenco/apizen-sdk-python
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: api,brasil,cep,cnpj,ibge,receita federal
|
|
10
|
+
Classifier: Natural Language :: Portuguese (Brazilian)
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# apizen-sdk
|
|
17
|
+
|
|
18
|
+
SDK oficial das APIs da [Apizen](https://www.apizen.com.br) para Python: CNPJ (Receita Federal, inclusive o CNPJ alfanumérico) e CEP (com código IBGE e coordenadas). Só a biblioteca padrão; Python 3.10+. Instala como `apizen-sdk` e importa como `apizen`.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install apizen-sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import os
|
|
26
|
+
from apizen import Apizen, is_valid_cnpj
|
|
27
|
+
|
|
28
|
+
apizen = Apizen(cnpj_key=os.environ["CNPJ_API_KEY"], cep_key=os.environ["CEPS_API_KEY"])
|
|
29
|
+
|
|
30
|
+
is_valid_cnpj("12.ABC.345/01DE-35") # True: só os dígitos verificadores, sem rede
|
|
31
|
+
|
|
32
|
+
empresa = apizen.cnpj("33.000.167/0001-01") # None quando o CNPJ não existe
|
|
33
|
+
print(empresa["razao_social"], empresa["ativa"])
|
|
34
|
+
|
|
35
|
+
nome = apizen.cnpj_nome("33000167000101") # só os nomes, mais leve
|
|
36
|
+
|
|
37
|
+
cep = apizen.cep("01001-000")
|
|
38
|
+
print(cep["municipio"]["codigo_ibge"], cep["localizacao"])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `cnpj`, `cnpj_nome`, `cep`: o recurso (um `dict`), ou `None` quando não existe (404).
|
|
42
|
+
- Outros erros (chave inválida, formato errado) levantam `ApizenError`, com `status`.
|
|
43
|
+
- `is_valid_cnpj`, `clean_cnpj`, `mask_cnpj`: CNPJ numérico e alfanumérico, sem rede.
|
|
44
|
+
|
|
45
|
+
Crie as suas chaves grátis em [apizen.com.br/entrar](https://www.apizen.com.br/entrar). Documentação: [apizen.com.br/docs](https://www.apizen.com.br/docs/inicio).
|
|
46
|
+
|
|
47
|
+
## Publicar uma versão
|
|
48
|
+
|
|
49
|
+
Mude `version` no `pyproject.toml` (e `__version__` em `src/apizen/__init__.py`), faça o commit e crie a tag `v<versão>` (`git tag v0.1.1 && git push origin v0.1.1`): o workflow `publish` testa, monta e publica no PyPI.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
apizen/__init__.py,sha256=ZzYmBzvyTVH69irxwSbkNdcMXoQwBssxrLlYxK3F5sU,440
|
|
2
|
+
apizen/client.py,sha256=esJHpC-BXlh6_qIthBVbzF2WfC5K8WTjF6UlAmH77UQ,2667
|
|
3
|
+
apizen/cnpj.py,sha256=tTQIXv06US_ZhJPt05fHX2plvd5xhGeD1u0ZDxTFDgU,1451
|
|
4
|
+
apizen/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
apizen_sdk-0.1.0.dist-info/METADATA,sha256=sSPs6yRVopEvTfzYHi9MExyaAecJpJEREP1kYYlud2A,2096
|
|
6
|
+
apizen_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
apizen_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=sDgL_LeiPsq4sIhuSBUrRzi8LbsTbI8OYpUG0KcVoUY,1063
|
|
8
|
+
apizen_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Apizen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|