Exemplo Completo Ponta a Ponta
Neste tutorial prático, você encontrará o código completo de uma mini-aplicação fullstack funcional integrando o SusConecta.
A aplicação demonstra a arquitetura recomendada em produção:
- Frontend (React): Painel de Cobertura Vacinal com selects dependentes (UF e Município), tabela analítica com tratamento de sigilo estatístico (SDC), estados visuais (loading, empty, error) e exportação local para CSV gerada no consumidor a partir do JSON da API (enquanto a API oferece nativamente geração de relatórios analíticos em formato XLSX via
POST /v1/analytics/exports/xlsxePOST /v1/analytics/export/xlsx). - Backend / BFF (Node.js Express): Camada intermediária que custodia a chave de API segura, faz cache e proxy para a SusConecta Data API.
🏗️ Arquitetura da Mini-Aplicação
sequenceDiagram
autonumber
actor User as Usuário (Navegador)
participant UI as React Frontend (Porta 3000)
participant BFF as Node.js BFF (Porta 3001)
participant API as SusConecta Data API (Produção)
User->>UI: Seleciona UF: "GO"
UI->>BFF: GET /api/municipalities?state=GO
BFF->>API: GET /v1/geo/municipalities?state_sigla=GO (Bearer Token)
API-->>BFF: 200 OK [Municípios de GO]
BFF-->>UI: 200 OK [Municípios]
UI-->>User: Popula Select de Municípios
User->>UI: Seleciona Município "Goiânia" e clica "Consultar"
UI->>BFF: GET /api/coverage?municipality_id=5208707&year=2024
BFF->>API: GET /v1/immunization/coverage/by-immunobiologic?municipality_id=5208707&year=2024 (Bearer Token)
API-->>BFF: 200 OK [Doses, População, Status SDC]
BFF-->>UI: 200 OK [Dados Processados]
UI-->>User: Renderiza Tabela com Células SDC Protegidas📁 Estrutura de Pastas do Projeto
Crie uma pasta para o projeto com a seguinte organização:
susconecta-demo/
├── package.json
├── .env
├── server/
│ └── index.mjs # Backend BFF com Express
└── src/
├── App.jsx # Painel React completo
├── index.jsx # Ponto de entrada React
└── styles.css # Estilização limpa1. Configuração do Projeto (package.json e .env)
package.json
{
"name": "susconecta-demo",
"version": "1.0.0",
"type": "module",
"scripts": {
"server": "node server/index.mjs",
"dev": "vite"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.0",
"vite": "^5.2.11"
}
}.env
Guarde sua chave de API real no backend (nunca envie para o Git):
PORT=3001
SUSCONECTA_API_URL=https://api.susconecta.com.br
SUSCONECTA_API_KEY=sua_chave_de_producao_ou_homologacao_aqui2. Backend BFF Seguro (server/index.mjs)
O BFF intermediador protege a credencial e impede requisições inseguras com apply_sdc=false:
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
const API_URL =
process.env.SUSCONECTA_API_URL || "https://api.susconecta.com.br";
const API_KEY = process.env.SUSCONECTA_API_KEY;
if (!API_KEY) {
console.error("[ERRO] SUSCONECTA_API_KEY não foi informada no arquivo .env!");
process.exit(1);
}
app.use(cors({ origin: "http://localhost:3000" }));
app.use(express.json());
// Helper para chamadas autenticadas à API Data SusConecta
async function callSusConecta(path, searchParams = {}) {
const url = new URL(`${API_URL}${path}`);
Object.entries(searchParams).forEach(([k, v]) => {
if (v !== undefined && v !== null && v !== "") {
url.searchParams.set(k, String(v));
}
});
const response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${API_KEY}`,
Accept: "application/json",
},
});
const data = await response.json();
return { status: response.status, data };
}
// 1. Rota de Municípios por Estado
app.get("/api/municipalities", async (req, res) => {
try {
const { state } = req.query;
if (!state) {
return res.status(400).json({ error: "Parâmetro state é obrigatório." });
}
const { status, data } = await callSusConecta("/v1/geo/municipalities", {
state_sigla: state,
limit: 300,
});
return res.status(status).json(data);
} catch (err) {
return res.status(500).json({
error: "Erro interno ao consultar municípios.",
details: err.message,
});
}
});
// 2. Rota de Cobertura Vacinal PNI por Imunobiológico
app.get("/api/coverage", async (req, res) => {
try {
const { municipality_id, year } = req.query;
if (!municipality_id || !year) {
return res
.status(400)
.json({ error: "municipality_id e year são obrigatórios." });
}
// O BFF sempre força o SDC canônico
const { status, data } = await callSusConecta(
"/v1/immunization/coverage/by-immunobiologic",
{
municipality_id,
year,
apply_sdc: "true",
},
);
return res.status(status).json(data);
} catch (err) {
return res.status(500).json({
error: "Erro interno ao consultar cobertura.",
details: err.message,
});
}
});
app.listen(PORT, () => {
console.log(`🚀 BFF SusConecta rodando em http://localhost:${PORT}`);
});3. Frontend React Completo (src/App.jsx)
Painel visual moderno com filtros, estados de carregamento, tratamento de dados nulos/suprimidos e exportação:
import React, { useState, useEffect } from "react";
const BFF_URL = "http://localhost:3001/api";
export default function App() {
const [states] = useState([
{ sigla: "GO", nome: "Goiás (246 municípios)" },
{ sigla: "MT", nome: "Mato Grosso (Escopo Piloto)" },
]);
const [selectedState, setSelectedState] = useState("GO");
const [municipalities, setMunicipalities] = useState([]);
const [selectedMunicipality, setSelectedMunicipality] = useState("");
const [selectedYear, setSelectedYear] = useState("2024");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [coverageData, setCoverageData] = useState(null);
// Carrega municípios quando o estado muda
useEffect(() => {
async function loadMunicipalities() {
try {
const res = await fetch(
`${BFF_URL}/municipalities?state=${selectedState}`,
);
const result = await res.json();
if (res.ok && result.data) {
setMunicipalities(result.data);
// Seleciona Goiânia como padrão em GO, ou o primeiro município em MT
const defaultMun =
result.data.find((m) => m.ibge_code === "5208707") ||
result.data[0];
setSelectedMunicipality(defaultMun ? defaultMun.ibge_code : "");
} else {
setError(result.error?.message || "Erro ao carregar municípios.");
}
} catch (err) {
setError("Não foi possível conectar ao servidor intermediário (BFF).");
}
}
loadMunicipalities();
}, [selectedState]);
// Consulta de cobertura
async function handleSearch(e) {
if (e) e.preventDefault();
if (!selectedMunicipality) return;
setLoading(true);
setError(null);
try {
const res = await fetch(
`${BFF_URL}/coverage?municipality_id=${selectedMunicipality}&year=${selectedYear}`,
);
const result = await res.json();
if (res.ok) {
setCoverageData(result);
} else {
setError(
result.error?.message || "Falha ao buscar indicadores de vacinação.",
);
}
} catch (err) {
setError("Erro de rede ao buscar dados.");
} finally {
setLoading(false);
}
}
// Exportação CSV gerada localmente no consumidor (browser) a partir dos dados JSON da API.
// (Nota: a SusConecta Data API oferece nativamente exportação estruturada em formato XLSX via POST /v1/analytics/exports/xlsx)
function exportCSV() {
if (!coverageData?.data?.length) return;
const headers = [
"Imunobiológico",
"Doses Computadas",
"População-Alvo",
"Taxa Calculada (%)",
"Status SDC",
];
const rows = coverageData.data.map((item) => [
`"${item.immunobiologic_name || "Desconhecido"}"`,
item.sdc_status === "SUPPRESSED" ? '"< 5"' : (item.doses_count ?? "0"),
item.target_population ?? "N/D",
item.sdc_status === "SUPPRESSED"
? '"—"'
: item.coverage_rate != null
? Number(item.coverage_rate).toFixed(2)
: "—",
`"${item.sdc_status || "CALCULATED"}"`,
]);
const csvContent =
"data:text/csv;charset=utf-8,\uFEFF" +
[headers.join(","), ...rows.map((r) => r.join(","))].join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute(
"download",
`cobertura_${selectedMunicipality}_${selectedYear}.csv`,
);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
return (
<div
style={{
maxWidth: 1000,
margin: "40px auto",
padding: "0 20px",
fontFamily: "sans-serif",
}}
>
<header
style={{
borderBottom: "2px solid #e2e8f0",
paddingBottom: 20,
marginBottom: 24,
}}
>
<h1 style={{ color: "#0f172a", margin: 0, fontSize: 24 }}>
Painel de Cobertura Vacinal (SI-PNI)
</h1>
<p style={{ color: "#64748b", margin: "6px 0 0" }}>
Demonstração de integração oficial com a API SusConecta via
Backend-For-Frontend.
</p>
</header>
{/* Formulário de Filtros */}
<form
onSubmit={handleSearch}
style={{
display: "flex",
gap: 16,
flexWrap: "wrap",
marginBottom: 24,
background: "#f8fafc",
padding: 20,
borderRadius: 8,
}}
>
<div
style={{ display: "flex", flexDirection: "column", minWidth: 160 }}
>
<label style={{ fontSize: 13, fontWeight: "bold", marginBottom: 6 }}>
Estado (UF):
</label>
<select
value={selectedState}
onChange={(e) => setSelectedState(e.target.value)}
style={{ padding: 8, borderRadius: 4, border: "1px solid #cbd5e1" }}
>
{states.map((s) => (
<option key={s.sigla} value={s.sigla}>
{s.nome}
</option>
))}
</select>
</div>
<div
style={{
display: "flex",
flexDirection: "column",
flex: 1,
minWidth: 240,
}}
>
<label style={{ fontSize: 13, fontWeight: "bold", marginBottom: 6 }}>
Município:
</label>
<select
value={selectedMunicipality}
onChange={(e) => setSelectedMunicipality(e.target.value)}
style={{ padding: 8, borderRadius: 4, border: "1px solid #cbd5e1" }}
>
{municipalities.map((m) => (
<option key={m.ibge_code} value={m.ibge_code}>
{m.name} ({m.ibge_code})
</option>
))}
</select>
</div>
<div
style={{ display: "flex", flexDirection: "column", minWidth: 120 }}
>
<label style={{ fontSize: 13, fontWeight: "bold", marginBottom: 6 }}>
Ano:
</label>
<select
value={selectedYear}
onChange={(e) => setSelectedYear(e.target.value)}
style={{ padding: 8, borderRadius: 4, border: "1px solid #cbd5e1" }}
>
<option value="2025">2025</option>
<option value="2024">2024</option>
<option value="2023">2023</option>
</select>
</div>
<div style={{ display: "flex", alignItems: "flex-end" }}>
<button
type="submit"
disabled={loading}
style={{
background: "#2563eb",
color: "#fff",
padding: "10px 20px",
border: "none",
borderRadius: 4,
cursor: "pointer",
fontWeight: "bold",
}}
>
{loading ? "Carregando..." : "Consultar"}
</button>
</div>
</form>
{/* Alertas de Erro */}
{error && (
<div
style={{
background: "#fee2e2",
color: "#991b1b",
padding: 16,
borderRadius: 6,
marginBottom: 20,
}}
>
<strong>Atenção:</strong> {error}
</div>
)}
{/* Resultados e Tabela */}
{coverageData && (
<div>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 12,
}}
>
<span style={{ fontSize: 14, color: "#475569" }}>
Mostrando {coverageData.data?.length || 0} imunobiológicos
computados
</span>
<button
onClick={exportCSV}
style={{
background: "#059669",
color: "#fff",
border: "none",
padding: "6px 14px",
borderRadius: 4,
cursor: "pointer",
fontSize: 13,
}}
>
📥 Exportar CSV
</button>
</div>
<table
style={{
width: "100%",
borderCollapse: "collapse",
textAlign: "left",
border: "1px solid #e2e8f0",
}}
>
<thead>
<tr
style={{
background: "#f1f5f9",
borderBottom: "2px solid #cbd5e1",
}}
>
<th style={{ padding: "10px 12px" }}>Imunobiológico</th>
<th style={{ padding: "10px 12px", textAlign: "right" }}>
Doses
</th>
<th style={{ padding: "10px 12px", textAlign: "right" }}>
População
</th>
<th style={{ padding: "10px 12px", textAlign: "right" }}>
Cobertura Calculada
</th>
<th style={{ padding: "10px 12px", textAlign: "center" }}>
Status SDC
</th>
</tr>
</thead>
<tbody>
{coverageData.data?.map((row, idx) => {
const isSuppressed = row.sdc_status === "SUPPRESSED";
return (
<tr key={idx} style={{ borderBottom: "1px solid #f1f5f9" }}>
<td style={{ padding: "10px 12px", fontWeight: 500 }}>
{row.immunobiologic_name}
</td>
<td style={{ padding: "10px 12px", textAlign: "right" }}>
{isSuppressed ? (
<span
style={{
background: "#fef3c7",
color: "#92400e",
padding: "2px 6px",
borderRadius: 4,
fontSize: 12,
fontWeight: "bold",
}}
>
< 5
</span>
) : (
(row.doses_count?.toLocaleString("pt-BR") ?? "0")
)}
</td>
<td
style={{
padding: "10px 12px",
textAlign: "right",
color: "#64748b",
}}
>
{row.target_population?.toLocaleString("pt-BR") ?? "—"}
</td>
<td
style={{
padding: "10px 12px",
textAlign: "right",
fontWeight: "bold",
}}
>
{isSuppressed
? "—"
: row.coverage_rate != null
? `${Number(row.coverage_rate).toFixed(2)}%`
: "—"}
</td>
<td style={{ padding: "10px 12px", textAlign: "center" }}>
<span
style={{
fontSize: 11,
padding: "2px 8px",
borderRadius: 999,
background: isSuppressed ? "#fed7aa" : "#bbf7d0",
color: isSuppressed ? "#9a3412" : "#166534",
}}
>
{isSuppressed ? "Sigilo Aplicado" : "Calculada"}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
<footer style={{ marginTop: 12, fontSize: 12, color: "#94a3b8" }}>
* Taxa calculada segundo nota metodológica oficial: (Doses
Computadas / População-Alvo) × 100. Contagens entre 1 e 4 doses são
suprimidas (< 5) para proteção de sigilo estatístico.
</footer>
</div>
)}
</div>
);
}4. Como Executar Localmente em 5 Passos
Instale as dependências:
bashnpm installConfigure o
.env: Preencha o arquivo.envna raiz do projeto com sua chave de API:iniSUSCONECTA_API_KEY=sua_chave_realInicie o servidor Backend/BFF (Terminal 1):
bashnpm run server # BFF ouvindo em http://localhost:3001Inicie a interface Frontend React (Terminal 2):
bashnpm run dev # Vite disponível em http://localhost:3000Acesse no navegador: Abra
http://localhost:3000e selecione um município (ex: Goiânia) para visualizar os indicadores em tempo real.