api-zen 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.
api_zen-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thiago
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.
api_zen-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: api-zen
3
+ Version: 0.1.0
4
+ Summary: Uma biblioteca Python de exemplo para demonstrar como criar pacotes pip.
5
+ Project-URL: Homepage, https://github.com/thiago/minha_biblioteca
6
+ Author-email: Thiago <trodriguessilva.dev@gmail.com>
7
+ License-File: LICENSE
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Requires-Dist: requests>=2.31.0
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ApiZen 🚀
16
+
17
+ Uma biblioteca Python moderna, leve e resiliente para simplificar a interação com APIs REST. Esqueça a configuração manual de retentativas, timeouts e headers de autenticação toda vez que for iniciar um novo projeto.
18
+
19
+ ---
20
+
21
+ ## ✨ Principais Recursos
22
+
23
+ - **Resiliência Integrada**: Retentativas automáticas (retries) para erros comuns de servidor (500, 502, 503, 504) e rate limit (429).
24
+ - **Logging Automático**: Feedback em tempo real no terminal sobre URLs chamadas, métodos, status de resposta e tempo de execução.
25
+ - **Sessões Persistentes**: Utiliza `requests.Session()` internamente para melhor performance.
26
+ - **Autenticação Simplificada**: Configure tokens Bearer ou outros esquemas com um único comando.
27
+ - **Tratamento de Erros**: Lança exceções automaticamente (`raise_for_status()`) para respostas de erro.
28
+
29
+ ---
30
+
31
+ ## 📦 Instalação
32
+
33
+ ### Instalação em modo desenvolvimento/local
34
+ Para testar a biblioteca localmente no seu ambiente virtual:
35
+
36
+ ```bash
37
+ # Ative seu venv primeiro
38
+ .\.venv\Scripts\Activate.ps1
39
+
40
+ # Instale em modo editável
41
+ pip install -e .
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 🚀 Como Usar
47
+
48
+ ### 1. Uso Básico (Rápido)
49
+ Para uma chamada única e rápida sem configurações:
50
+
51
+ ```python
52
+ from api_zen import request_api
53
+
54
+ data = request_api("https://api.github.com")
55
+ print(data)
56
+ ```
57
+
58
+ ### 2. Uso Profissional (ApiZen)
59
+ Recomendado para projetos que interagem com uma API especĂ­fica:
60
+
61
+ ```python
62
+ from api_zen import ApiZen
63
+
64
+ # Configura o cliente uma Ăşnica vez
65
+ api = ApiZen(
66
+ base_url="https://api.exemplo.com", # URL base para todos os endpoints
67
+ timeout=10, # Tempo limite de espera (segundos)
68
+ max_retries=3 # NĂşmero de tentativas em caso de erro
69
+ )
70
+
71
+ # Configura autenticação Bearer
72
+ api.set_token("seu_token_aqui")
73
+
74
+ # Faz a chamada e recebe o JSON já convertido
75
+ usuarios = api.get("usuarios")
76
+ ```
77
+
78
+ ### 3. Métodos Suportados
79
+ A classe `ApiZen` suporta os principais verbos HTTP:
80
+
81
+ ```python
82
+ api.get("endpoint", params={"id": 1})
83
+ api.post("endpoint", json={"nome": "Thiago"})
84
+ api.put("endpoint", json={"status": "ativo"})
85
+ api.delete("endpoint")
86
+ ```
87
+
88
+ ---
89
+
90
+ ## 🛠️ Estrutura do Projeto
91
+
92
+ ```text
93
+ api-zen/
94
+ ├── pyproject.toml # Configurações de build e dependências
95
+ ├── README.md # Esta documentação
96
+ ├── src/
97
+ │ └── api_zen/ # Corrigido: underscore para importação
98
+ │ ├── __init__.py # Exportação da API pública
99
+ │ └── core.py # Lógica robusta com ApiZen
100
+ └── tests/
101
+ └── verify_install.py # Script de teste rápido
102
+ ```
103
+
104
+ ---
105
+
106
+ ## đź“– DependĂŞncias
107
+
108
+ - `requests`: A base sólida para comunicações HTTP.
109
+ - `urllib3`: Gerenciamento avançado de retentativas.
110
+
111
+ ---
112
+
113
+ ## 🤝 Contribuindo
114
+
115
+ Sinta-se à vontade para sugerir melhorias ou abrir issues! Esta biblioteca foi criada para ser o ponto de partida ideal para qualquer integração de API em Python.
116
+
117
+ ---
118
+
119
+ ## 📄 Licença
120
+
121
+ Este projeto está sob a licença [MIT](LICENSE).
@@ -0,0 +1,107 @@
1
+ # ApiZen 🚀
2
+
3
+ Uma biblioteca Python moderna, leve e resiliente para simplificar a interação com APIs REST. Esqueça a configuração manual de retentativas, timeouts e headers de autenticação toda vez que for iniciar um novo projeto.
4
+
5
+ ---
6
+
7
+ ## ✨ Principais Recursos
8
+
9
+ - **Resiliência Integrada**: Retentativas automáticas (retries) para erros comuns de servidor (500, 502, 503, 504) e rate limit (429).
10
+ - **Logging Automático**: Feedback em tempo real no terminal sobre URLs chamadas, métodos, status de resposta e tempo de execução.
11
+ - **Sessões Persistentes**: Utiliza `requests.Session()` internamente para melhor performance.
12
+ - **Autenticação Simplificada**: Configure tokens Bearer ou outros esquemas com um único comando.
13
+ - **Tratamento de Erros**: Lança exceções automaticamente (`raise_for_status()`) para respostas de erro.
14
+
15
+ ---
16
+
17
+ ## 📦 Instalação
18
+
19
+ ### Instalação em modo desenvolvimento/local
20
+ Para testar a biblioteca localmente no seu ambiente virtual:
21
+
22
+ ```bash
23
+ # Ative seu venv primeiro
24
+ .\.venv\Scripts\Activate.ps1
25
+
26
+ # Instale em modo editável
27
+ pip install -e .
28
+ ```
29
+
30
+ ---
31
+
32
+ ## 🚀 Como Usar
33
+
34
+ ### 1. Uso Básico (Rápido)
35
+ Para uma chamada única e rápida sem configurações:
36
+
37
+ ```python
38
+ from api_zen import request_api
39
+
40
+ data = request_api("https://api.github.com")
41
+ print(data)
42
+ ```
43
+
44
+ ### 2. Uso Profissional (ApiZen)
45
+ Recomendado para projetos que interagem com uma API especĂ­fica:
46
+
47
+ ```python
48
+ from api_zen import ApiZen
49
+
50
+ # Configura o cliente uma Ăşnica vez
51
+ api = ApiZen(
52
+ base_url="https://api.exemplo.com", # URL base para todos os endpoints
53
+ timeout=10, # Tempo limite de espera (segundos)
54
+ max_retries=3 # NĂşmero de tentativas em caso de erro
55
+ )
56
+
57
+ # Configura autenticação Bearer
58
+ api.set_token("seu_token_aqui")
59
+
60
+ # Faz a chamada e recebe o JSON já convertido
61
+ usuarios = api.get("usuarios")
62
+ ```
63
+
64
+ ### 3. Métodos Suportados
65
+ A classe `ApiZen` suporta os principais verbos HTTP:
66
+
67
+ ```python
68
+ api.get("endpoint", params={"id": 1})
69
+ api.post("endpoint", json={"nome": "Thiago"})
70
+ api.put("endpoint", json={"status": "ativo"})
71
+ api.delete("endpoint")
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 🛠️ Estrutura do Projeto
77
+
78
+ ```text
79
+ api-zen/
80
+ ├── pyproject.toml # Configurações de build e dependências
81
+ ├── README.md # Esta documentação
82
+ ├── src/
83
+ │ └── api_zen/ # Corrigido: underscore para importação
84
+ │ ├── __init__.py # Exportação da API pública
85
+ │ └── core.py # Lógica robusta com ApiZen
86
+ └── tests/
87
+ └── verify_install.py # Script de teste rápido
88
+ ```
89
+
90
+ ---
91
+
92
+ ## đź“– DependĂŞncias
93
+
94
+ - `requests`: A base sólida para comunicações HTTP.
95
+ - `urllib3`: Gerenciamento avançado de retentativas.
96
+
97
+ ---
98
+
99
+ ## 🤝 Contribuindo
100
+
101
+ Sinta-se à vontade para sugerir melhorias ou abrir issues! Esta biblioteca foi criada para ser o ponto de partida ideal para qualquer integração de API em Python.
102
+
103
+ ---
104
+
105
+ ## 📄 Licença
106
+
107
+ Este projeto está sob a licença [MIT](LICENSE).
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "api-zen"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="Thiago", email="trodriguessilva.dev@gmail.com" },
10
+ ]
11
+ description = "Uma biblioteca Python de exemplo para demonstrar como criar pacotes pip."
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ dependencies = [
15
+ "requests>=2.31.0",
16
+ ]
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ ]
22
+
23
+ [project.urls]
24
+ "Homepage" = "https://github.com/thiago/minha_biblioteca"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/api_zen"]
@@ -0,0 +1,3 @@
1
+ from .core import ApiZen, request_api
2
+
3
+ __all__ = ["ApiZen", "request_api"]
@@ -0,0 +1,73 @@
1
+ import requests
2
+ import logging
3
+ from urllib3.util.retry import Retry
4
+ from requests.adapters import HTTPAdapter
5
+ import time
6
+
7
+ # Configuração básica de logging
8
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
+ logger = logging.getLogger("ApiZen")
10
+
11
+ class ApiZen:
12
+ """
13
+ Uma classe facilitadora e robusta para fazer requisições a APIs REST.
14
+ """
15
+ def __init__(self, base_url: str = "", headers: dict = None, timeout: int = 10, max_retries: int = 3):
16
+ self.base_url = base_url.rstrip("/")
17
+ self.headers = headers or {}
18
+ self.timeout = timeout
19
+ self.session = requests.Session()
20
+ self.session.headers.update(self.headers)
21
+
22
+ # Configuração de Retentativas (Resiliência)
23
+ retry_strategy = Retry(
24
+ total=max_retries,
25
+ backoff_factor=1,
26
+ status_forcelist=[429, 500, 502, 503, 504],
27
+ )
28
+ adapter = HTTPAdapter(max_retries=retry_strategy)
29
+ self.session.mount("http://", adapter)
30
+ self.session.mount("https://", adapter)
31
+
32
+ def set_token(self, token: str, scheme: str = "Bearer"):
33
+ """Define o token de autenticação nos headers."""
34
+ self.session.headers.update({"Authorization": f"{scheme} {token}"})
35
+ logger.info(f"Token de autenticação ({scheme}) configurado.")
36
+
37
+ def _get_url(self, endpoint: str) -> str:
38
+ if endpoint.startswith("http"):
39
+ return endpoint
40
+ return f"{self.base_url}/{endpoint.lstrip('/')}"
41
+
42
+ def _request(self, method: str, endpoint: str, **kwargs):
43
+ url = self._get_url(endpoint)
44
+ logger.info(f"Chamando {method} em: {url}")
45
+
46
+ start_time = time.time()
47
+ try:
48
+ kwargs.setdefault("timeout", self.timeout)
49
+ response = self.session.request(method, url, **kwargs)
50
+ duration = time.time() - start_time
51
+
52
+ logger.info(f"Resposta: {response.status_code} ({duration:.2f}s)")
53
+ response.raise_for_status()
54
+ return response.json()
55
+ except requests.exceptions.RequestException as e:
56
+ logger.error(f"Erro na requisição: {e}")
57
+ raise
58
+
59
+ def get(self, endpoint: str, params: dict = None):
60
+ return self._request("GET", endpoint, params=params)
61
+
62
+ def post(self, endpoint: str, data: dict = None, json: dict = None):
63
+ return self._request("POST", endpoint, data=data, json=json)
64
+
65
+ def put(self, endpoint: str, data: dict = None, json: dict = None):
66
+ return self._request("PUT", endpoint, data=data, json=json)
67
+
68
+ def delete(self, endpoint: str):
69
+ return self._request("DELETE", endpoint)
70
+
71
+ def request_api(api: str):
72
+ """Mantendo para compatibilidade simples."""
73
+ return ApiZen().get(api)
@@ -0,0 +1,20 @@
1
+ from api_zen import ApiZen
2
+ import logging
3
+
4
+ # Opcional: VocĂŞ pode mudar o nĂ­vel do log se quiser menos detalhes
5
+ # logging.getLogger("ApiZen").setLevel(logging.WARNING)
6
+
7
+ print("--- Testando ApiZen ---")
8
+
9
+ # 1. Base URL e Logging Automático
10
+ api = ApiZen(base_url="https://api.disneyapi.dev", timeout=5)
11
+
12
+ # 2. Helper de Autenticação
13
+ api.set_token("meu_token_secreto")
14
+
15
+ print("\nFazendo requisição:")
16
+ try:
17
+ data = api.get("character")
18
+ print(f"\nSucesso! Recebemos dados de {len(data['data'])} personagens.")
19
+ except Exception as e:
20
+ print(f"\nErro no teste: {e}")