Skip to main content

SDK Python

O SDK Python está em desenvolvimento. Os exemplos abaixo mostram como integrar usando httpx diretamente enquanto o pacote não é publicado no PyPI.

Integração direta com httpx

import httpx

class EngineAPI:
    def __init__(self, base_url: str, api_key: str):
        self.client = httpx.Client(
            base_url=base_url,
            headers={"x-api-key": api_key},
            timeout=30.0,
        )

    def emitir_nfe(self, dados: dict) -> dict:
        response = self.client.post("/v1/nfe", json=dados)
        response.raise_for_status()
        return response.json()

    def listar_nfes(self, page: int = 1, limit: int = 20) -> dict:
        response = self.client.get("/v1/nfe", params={"page": page, "limit": limit})
        response.raise_for_status()
        return response.json()

    def cancelar_nfe(self, access_key: str, motivo: str) -> dict:
        response = self.client.post(
            f"/v1/nfe/{access_key}/cancelar",
            json={"motivo": motivo}
        )
        response.raise_for_status()
        return response.json()

    def download_pdf(self, access_key: str) -> bytes:
        response = self.client.get(f"/v1/nfe/pdf/{access_key}")
        response.raise_for_status()
        return response.content

    def download_xml(self, access_key: str) -> bytes:
        response = self.client.get(f"/v1/nfe/xml/{access_key}")
        response.raise_for_status()
        return response.content

Uso

engine = EngineAPI(
    base_url="https://api.engineapi.com.br",
    api_key="ek_live_SEU_API_KEY",
)

# Emitir NFe
nfe = engine.emitir_nfe({
    "issuerId": "ISSUER_UUID",
    "naturezaOperacao": "VENDA DE MERCADORIA",
    "destinatario": {
        "cnpj": "99888777000155",
        "nome": "Cliente Exemplo SA",
        "indicadorIE": 9,
        "endereco": {
            "logradouro": "Av Brasil", "numero": "500",
            "bairro": "Centro", "codigoMunicipio": "3550308",
            "municipio": "São Paulo", "uf": "SP", "cep": "01001000",
        },
    },
    "itens": [{
        "numero": 1, "codigo": "PROD001",
        "descricao": "Camiseta Azul M", "ncm": "61091000",
        "cfop": "5102", "unidade": "UN", "quantidade": 1,
        "valorUnitario": 89.90, "valorTotal": 89.90,
        "icms": {"origem": 0, "csosn": "400"},
    }],
    "pagamento": {"forma": "01", "valor": 89.90},
})

print(f"NFe autorizada: {nfe['data']['accessKey']}")

Versão async (FastAPI)

import httpx

class EngineAPIAsync:
    def __init__(self, base_url: str, api_key: str):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={"x-api-key": api_key},
            timeout=30.0,
        )

    async def emitir_nfe(self, dados: dict) -> dict:
        response = await self.client.post("/v1/nfe", json=dados)
        response.raise_for_status()
        return response.json()

# FastAPI
from fastapi import FastAPI
app = FastAPI()
engine = EngineAPIAsync("https://api.engineapi.com.br", "ek_live_KEY")

@app.post("/nfe")
async def emitir(dados: dict):
    return await engine.emitir_nfe(dados)

Tratamento de erros

import httpx

try:
    nfe = engine.emitir_nfe(dados)
except httpx.HTTPStatusError as e:
    if e.response.status_code == 400:
        print("Dados inválidos:", e.response.json())
    elif e.response.status_code == 422:
        # Rejeição SEFAZ
        erro = e.response.json()
        print(f"Rejeição {erro['sefazCode']}: {erro['sefazMessage']}")
    elif e.response.status_code == 429:
        print("Rate limit — aguarde e tente novamente")
    else:
        print(f"Erro {e.response.status_code}: {e.response.text}")

Próximos passos

SDK TypeScript

SDK oficial com tipagem completa

API Reference

Documentação completa de todos os endpoints