apizen-sdk 0.1.0__tar.gz

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,7 @@
1
+ {
2
+ "attribution": {
3
+ "commit": "",
4
+ "pr": "",
5
+ "sessionUrl": false
6
+ }
7
+ }
@@ -0,0 +1,21 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python: ["3.10", "3.11", "3.12", "3.13", "3.14"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: ${{ matrix.python }}
19
+ - run: python -m unittest discover -s tests -v
20
+ env:
21
+ PYTHONPATH: src
@@ -0,0 +1,41 @@
1
+ name: publish
2
+
3
+ # A v* tag publishes that version to PyPI as "apizen-sdk" (imported as apizen). Trusted publishing (OIDC): PyPI
4
+ # trusts this workflow of this repository, so no token is stored anywhere.
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: "3.13"
17
+ - name: tag matches pyproject.toml
18
+ run: |
19
+ version=$(sed -n 's/^version = "\(.*\)"/\1/p' pyproject.toml | head -1)
20
+ [ "${GITHUB_REF_NAME}" = "v$version" ] || { echo "tag ${GITHUB_REF_NAME}, pyproject $version"; exit 1; }
21
+ - run: python -m unittest discover -s tests
22
+ env:
23
+ PYTHONPATH: src
24
+ - run: python -m pip install build && python -m build
25
+ - uses: actions/upload-artifact@v4
26
+ with:
27
+ name: dist
28
+ path: dist/
29
+
30
+ publish:
31
+ needs: build
32
+ runs-on: ubuntu-latest
33
+ environment: pypi
34
+ permissions:
35
+ id-token: write
36
+ steps:
37
+ - uses: actions/download-artifact@v4
38
+ with:
39
+ name: dist
40
+ path: dist/
41
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ .DS_Store
@@ -0,0 +1,8 @@
1
+ # apizen-sdk-python
2
+
3
+ ## Commits and comments
4
+
5
+ - Code comments, docs and commit messages are always in English.
6
+ - Commits follow [Conventional Commits](https://www.conventionalcommits.org): `type(scope): subject`, with `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore` or `revert`.
7
+ - Keep the subject short (about 60 characters at most), in the imperative, without a final period. One change per commit: small, focused commits.
8
+ - No AI attribution in commits or pull requests (no `Co-Authored-By` or "Generated with" lines).
@@ -0,0 +1 @@
1
+ AGENTS.md
@@ -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.
@@ -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,34 @@
1
+ # apizen-sdk
2
+
3
+ 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`.
4
+
5
+ ```bash
6
+ pip install apizen-sdk
7
+ ```
8
+
9
+ ```python
10
+ import os
11
+ from apizen import Apizen, is_valid_cnpj
12
+
13
+ apizen = Apizen(cnpj_key=os.environ["CNPJ_API_KEY"], cep_key=os.environ["CEPS_API_KEY"])
14
+
15
+ is_valid_cnpj("12.ABC.345/01DE-35") # True: só os dígitos verificadores, sem rede
16
+
17
+ empresa = apizen.cnpj("33.000.167/0001-01") # None quando o CNPJ não existe
18
+ print(empresa["razao_social"], empresa["ativa"])
19
+
20
+ nome = apizen.cnpj_nome("33000167000101") # só os nomes, mais leve
21
+
22
+ cep = apizen.cep("01001-000")
23
+ print(cep["municipio"]["codigo_ibge"], cep["localizacao"])
24
+ ```
25
+
26
+ - `cnpj`, `cnpj_nome`, `cep`: o recurso (um `dict`), ou `None` quando não existe (404).
27
+ - Outros erros (chave inválida, formato errado) levantam `ApizenError`, com `status`.
28
+ - `is_valid_cnpj`, `clean_cnpj`, `mask_cnpj`: CNPJ numérico e alfanumérico, sem rede.
29
+
30
+ 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).
31
+
32
+ ## Publicar uma versão
33
+
34
+ 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,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "apizen-sdk"
7
+ version = "0.1.0"
8
+ description = "SDK oficial das APIs da Apizen: CNPJ (Receita Federal) e CEP (com código IBGE e coordenadas)."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ keywords = ["cnpj", "cep", "receita federal", "ibge", "brasil", "api"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Natural Language :: Portuguese (Brazilian)",
16
+ "Typing :: Typed",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://www.apizen.com.br/docs/sdks"
21
+ Source = "https://github.com/apizenco/apizen-sdk-python"
22
+
23
+ # Installed as apizen-sdk, imported as apizen.
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/apizen"]
@@ -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"
@@ -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
@@ -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}"
File without changes
@@ -0,0 +1,53 @@
1
+ import io
2
+ import json
3
+ import unittest
4
+ import urllib.error
5
+ from unittest import mock
6
+
7
+ from apizen import Apizen, ApizenError, clean_cnpj, is_valid_cnpj, mask_cnpj
8
+
9
+
10
+ class Cnpj(unittest.TestCase):
11
+ def test_check_digits(self):
12
+ self.assertTrue(is_valid_cnpj("33.000.167/0001-01"))
13
+ self.assertFalse(is_valid_cnpj("33.000.167/0001-02"))
14
+ self.assertTrue(is_valid_cnpj("12.ABC.345/01DE-35"))
15
+ self.assertFalse(is_valid_cnpj("11.111.111/1111-11"))
16
+ self.assertEqual(clean_cnpj("12.abc.345/01de-35"), "12ABC34501DE35")
17
+ self.assertEqual(mask_cnpj("33000167000101"), "33.000.167/0001-01")
18
+
19
+
20
+ class Response(io.BytesIO):
21
+ def __enter__(self):
22
+ return self
23
+
24
+ def __exit__(self, *a):
25
+ return False
26
+
27
+
28
+ def http_error(code, body):
29
+ return urllib.error.HTTPError("u", code, "x", {}, io.BytesIO(json.dumps(body).encode()))
30
+
31
+
32
+ class Client(unittest.TestCase):
33
+ def test_cnpj(self):
34
+ with mock.patch("urllib.request.urlopen", return_value=Response(b'{"cnpj": "33000167000101"}')) as m:
35
+ r = Apizen(cnpj_key="sk_cnpj_x").cnpj("33.000.167/0001-01")
36
+ self.assertEqual(r["cnpj"], "33000167000101")
37
+ req = m.call_args[0][0]
38
+ self.assertEqual(req.full_url, "https://cnpj.apizen.com.br/v1/cnpj/33000167000101")
39
+ self.assertEqual(req.get_header("Authorization"), "Bearer sk_cnpj_x")
40
+
41
+ def test_not_found_and_errors(self):
42
+ with mock.patch("urllib.request.urlopen", side_effect=http_error(404, {"error": "cep not found"})):
43
+ self.assertIsNone(Apizen(cep_key="k").cep("01001-000"))
44
+ with mock.patch("urllib.request.urlopen", side_effect=http_error(401, {"error": "invalid or revoked key"})):
45
+ with self.assertRaises(ApizenError) as e:
46
+ Apizen(cnpj_key="k").cnpj_nome("33000167000101")
47
+ self.assertEqual(e.exception.status, 401)
48
+ with self.assertRaises(ApizenError):
49
+ Apizen().cep("01001000")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ unittest.main()