Skip to main content

notifica-govbr

Biblioteca Python para envio de notificações à Caixa Postal Digital do cidadão, com entrega opcional por push no aplicativo gov.br, via API do SERPRO.

Público-alvo: órgãos e entidades da Administração Pública com acesso à API de envio de mensagens da Caixa Postal.

Instalação

pip install notifica-govbr

Pré-requisitos

  • API key fornecida pelo SERPRO para o seu órgão.
  • Template cadastrado previamente no serviço. A biblioteca referencia um template_id; ela não cria templates.

Uso básico

from notifica_govbr import (
    HttpNotificationAdapter,
    NotificaClient,
    Notification,
    Recipient,
)

adapter = HttpNotificationAdapter(
    base_url="https://h-api-orgaos-cxpostal.np.estaleiro.serpro.gov.br",  # homologação
    api_key="sua-api-key",
)

client = NotificaClient(adapter)

response = client.send(
    Notification(
        subject="Olá, cidadão",
        recipients=[
            Recipient(cpf="12345678901", tags={"nome": "Maria"}),
        ],
        has_push=True,
        template_id=42,
        version=1,
        tags={"documento": "CNH"},
    )
)

print(response.cpf_successes)   # ['12345678901']
print(response.failed)          # []  ou  [FailedSend(cpfs=[...], reason='...')]

O adaptador HTTP gerencia o ciclo de vida da conexão e pode ser usado como context manager:

with HttpNotificationAdapter(base_url=..., api_key=...) as adapter:
    client = NotificaClient(adapter)
    client.send(...)

Testes com a API fake

A biblioteca inclui um adaptador em memória para testar o seu código sem rede. Ele implementa a mesma porta do adaptador HTTP e registra o que foi enviado:

from notifica_govbr import FakeNotificationAdapter, NotificaClient

fake = FakeNotificationAdapter()
client = NotificaClient(fake)

client.send(...)

assert fake.sent[0].subject == "Olá, cidadão"

Para simular falhas por CPF:

fake = FakeNotificationAdapter(
    failing_cpfs={"98765432100"},
    failure_reason="CPF não encontrado",
)
response = NotificaClient(fake).send(...)

assert response.failed[0].cpfs == ["98765432100"]
assert response.failed[0].reason == "CPF não encontrado"

Formato da resposta

SendResponse reflete o contrato da API (falhas/sucessos):

  • response.cpf_successes: list[str] — CPFs processados com sucesso.
  • response.failed: list[FailedSend] — falhas agrupadas por motivo.
    • FailedSend.cpfs: list[str]
    • FailedSend.reason: str

Falhas por destinatário vêm no SendResponse. Falhas de transporte (timeout, 401, 5xx) viram exceções httpx.HTTPError — o usuário trata os dois casos em lugares diferentes, sem misturar.

API pública

from notifica_govbr import (
    FailedSend,
    FakeNotificationAdapter,
    HttpNotificationAdapter,
    NotificaClient,
    Notification,
    NotificationPort,
    Recipient,
    SendResponse,
)

NotificationPort é o Protocol que qualquer adaptador precisa cumprir. Use-o apenas se quiser implementar um adaptador próprio (ex: cache, fila, outro transporte). Para o uso comum, basta HttpNotificationAdapter ou FakeNotificationAdapter.

Status

Versão 0.1.0 — adaptador síncrono (httpx.Client). Versão assíncrona (httpx.AsyncClient) planejada para uma versão futura, sem quebrar a API atual.

Licença

Este projeto está licenciado sob a Apache License 2.0. Veja o arquivo LICENSE para o texto completo.

Metadata

Release files for notifica-govbr 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for notifica-govbr 0.1.0
File Size Uploaded Provenance Actions
notifica_govbr-0.1.0.tar.gz 9.8 kB Without provenance Details for notifica_govbr-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for notifica-govbr 0.1.0
File Interpreter ABI Platform Actions
notifica_govbr-0.1.0-py3-none-any.whl Python 3 none any Details for notifica_govbr-0.1.0-py3-none-any.whl

Total release size: 22.8 kB

Release files / notifica_govbr-0.1.0.tar.gz

Download URL notifica_govbr-0.1.0.tar.gz
Size 9.8 kB
Tags Source
SHA-256 checksum
How to use checksums
2a716107d76ca415978b0a3c9c9a9e8df7965bd1d6b99a5cfe9df6101a8aab91
BLAKE2b-256 checksum
How to use checksums
a8325e454afcad73c08ff46cd05be436ebddfe437026c476df58471ecb6e8132
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / notifica_govbr-0.1.0-py3-none-any.whl

Download URL notifica_govbr-0.1.0-py3-none-any.whl
Size 13.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
86596a94669506ece38d00f3c653ef3ea7f350b5b5fbf10df98019892379c0b9
BLAKE2b-256 checksum
How to use checksums
04466f91d803892a9ac49ca9e03f1f8a530d6efa806cd0cffa53b39925ea47e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for notifica-govbr 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page