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"

Integração com FastAPI

A biblioteca inclui um helper que lê as configurações via pydantic-settings e monta o NotificaClient pronto para ser usado com Depends.

Instale o extra:

pip install "notifica-govbr[fastapi]"

Configure as variáveis de ambiente (ou um arquivo .env):

NOTIFICA_BASE_URL=https://h-api-orgaos-cxpostal.np.estaleiro.serpro.gov.br
NOTIFICA_API_KEY=sua-api-key

Use a dependency pronta:

from fastapi import Depends, FastAPI
from notifica_govbr import NotificaClient
from notifica_govbr.integracao.fastapi import get_notifica_client

app = FastAPI()

@app.post("/notificar")
def notificar(client: NotificaClient = Depends(get_notifica_client)):
    return client.send(...)

Nos testes, sobrescreva a dependency para usar o fake:

from notifica_govbr import FakeNotificationAdapter, NotificaClient

def override():
    return NotificaClient(FakeNotificationAdapter())

app.dependency_overrides[get_notifica_client] = override

Integração com Django

Instale o extra:

pip install "notifica-govbr[django]"

Configure as settings no settings.py do seu projeto:

NOTIFICA_BASE_URL = "https://h-api-orgaos-cxpostal.np.estaleiro.serpro.gov.br"
NOTIFICA_API_KEY = "sua-api-key"

Use o helper nas views ou services:

from notifica_govbr.integracao.django import get_notifica_client

def minha_view(request):
    client = get_notifica_client()
    return client.send(...)

Assim como no FastAPI, o helper apenas monta o cliente; o gerenciamento do ciclo de vida e o tratamento de exceções ficam a cargo da sua aplicação.

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.1

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.1
File Size Uploaded Provenance Actions
notifica_govbr-0.1.1.tar.gz 10.3 kB Without provenance Details for notifica_govbr-0.1.1.tar.gz

Built distribution (wheel)

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

Total release size: 23.8 kB

Release files / notifica_govbr-0.1.1.tar.gz

Download URL notifica_govbr-0.1.1.tar.gz
Size 10.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e089c13e116c1bceda3b9bb831923db72bfeca0d14e7eb7186009724fc7c9e2b
BLAKE2b-256 checksum
How to use checksums
310f591831827221ede4baf41520725f0f22877f8f6e47bd5ae2bd7bbfbd312f
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.1-py3-none-any.whl

Download URL notifica_govbr-0.1.1-py3-none-any.whl
Size 13.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f35a1293e2d4cc7169ad1e39fc9c3178ac15f0692fee3ba1eb0360b8d2d26dee
BLAKE2b-256 checksum
How to use checksums
30d006e9da271c43c156eeda89f27681602d2baff530d23f2260b9cf3768da2a
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.1

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.1 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