Learn R Programming

tesouror

tesouror provides a unified R interface to the Brazilian National Treasury (Tesouro Nacional) open data APIs. It covers five major data sources:

APIDataFunctions
SICONFIFiscal reports (RREO, RGF, DCA, MSC), entitiesget_rreo(), get_rgf(), get_dca(), ...
CUSTOSFederal government costsget_custos_pessoal_ativo(), ...
SADIPEMPublic debt & credit operations (PVL)get_pvl(), get_opc_*(), get_res_*()
SIORGFederal organizational structure (dictionary for CUSTOS)get_siorg_orgaos(), get_siorg_estrutura()
TransferênciasConstitutional transfers to states/municipalitiesget_tc_*()
SIOPEEducation spending (FNDE/MEC)get_siope_dados_gerais(), get_siope_despesas(), ...

All functions return tidy tibbles and have both Portuguese (matching API parameter names) and English aliases.

Installation

# From CRAN (when available):
install.packages("tesouror")

# Development version:
# remotes::install_github("StrategicProjects/tesouror")

Quick start

library(tesouror)

# List government entities
entes <- get_entes()

# RREO for Tocantins
rreo <- get_budget_report(
  fiscal_year = 2022, period = 6, report_type = "RREO",
  appendix = "RREO-Anexo 01", sphere = "E", entity_id = 17
)

# Federal government active staff costs (always filter by org AND month!
# the CUSTOS backend is slow; year-wide queries often hit HTTP 504)
custos <- get_costs_active_staff(
  year = 2023, month = 6,
  org_level1 = 244, org_level2 = 249  # MEC > INEP
)
# If pagination fails mid-way the package returns a partial result;
# check `attr(custos, "partial")` and `attr(custos, "last_page_error")`.

# Constitutional transfers (codes are Treasury-internal, NOT IBGE!)
estados <- get_tc_states()
pe <- estados$codigo[estados$nome == "Pernambuco"]
tc <- get_tc_by_state(state_code = pe, year = 2023)

# Public debt requests for PE
pvl <- get_debt_requests(state = "PE")

# SIORG: look up organization codes for CUSTOS queries
orgaos <- get_siorg_organizations(power_code = 1, sphere_code = 1)
# Use orgaos$codigo_unidade as org_level1 in get_costs_active_staff()

# SIOPE: education spending data
indicadores <- get_siope_indicators(year = 2023, period = 6, state = "PE")

# Clear the cache if needed
tesouror_clear_cache()

Features

  • Bilingual: Portuguese and English function/parameter names
  • Caching: In-memory cache avoids repeated API calls
  • Pagination: Automatic handling of multi-page responses with progress
  • verbose mode: Print full API URLs for debugging (verbose = TRUE or options(tesouror.verbose = TRUE))
  • page_size control: Tune rows per page for speed vs. stability
  • Clean output: janitor::clean_names() ensures consistent snake_case columns
  • Friendly errors: Retries with informative messages; NA validation on required params
  • Tidy output: All results are tibbles

Migrating from siconfir

tesouror is a superset of siconfir. All SICONFI functions work exactly the same. The cache-clearing function is now tesouror_clear_cache():

tesouror_clear_cache()

Documentation

See the package website at https://strategicprojects.github.io/tesouror/ for full documentation and vignettes.

Architecture

API Reference

SICONFI — Fiscal Reports

https://apidatalake.tesouro.gov.br/ords/siconfi/tt/

Provides fiscal reports (RREO, RGF, DCA), accounting matrices (MSC), and a government entity registry. Maintained by STN (Secretaria do Tesouro Nacional).

DetailValue
PaginationORDS (hasMore/offset), automatic
Default page sizeServer default (5,000 rows)
Retries5 attempts, progressive backoff (3s, 6s, 9s...)
max_rowsSupported
Functions18 (9 PT + 9 EN)

CUSTOS — Federal Government Costs

https://apidatalake.tesouro.gov.br/ords/custos/tt/

Cost data for active/retired staff, pensioners, depreciation, transfers, and other costs. Broken down by organization hierarchy (SIORG codes) and demographics.

DetailValue
PaginationORDS (hasMore/offset), automatic
Default page size500 rows (lowered from 1000 in 0.2.1: the backend timed out on broad queries)
Retries5 attempts, progressive backoff (3s, 6s, 9s...)
max_rowsSupported
Partial resultsWhen pagination fails mid-way, the package returns what was fetched with attr(result, "partial") = TRUE
SIORG code paddingAutomatic (244"000244")
Functions12 (6 PT + 6 EN)

Warning: The CUSTOS API is slow. Always filter by organizacao_n1

  • organizacao_n2 (or org_level1 + org_level2) and by mes /

month to avoid HTTP 504 timeouts. Use max_rows for quick tests. Year-wide queries with no month filter routinely time out the upstream load balancer.

SADIPEM — Public Debt

https://apidatalake.tesouro.gov.br/ords/sadipem/tt/

Public debt verification letters (PVL), credit operations, payment schedules, exchange rates, and debt capacity results.

DetailValue
PaginationORDS (hasMore/offset), automatic
Default page sizeServer default (5,000 rows)
Retries5 attempts, progressive backoff
max_rowsSupported
Functions14 (7 PT + 7 EN)

Transferências Constitucionais

https://apiapex.tesouro.gov.br/aria/v1/transferencias_constitucionais/custom/

Constitutional transfers (FPE, FPM, FUNDEB, etc.) to states and municipalities. Uses Treasury-internal codes (not IBGE codes) — use the dictionary functions to look them up.

DetailValue
PaginationNone (single response)
Retries5 attempts, progressive backoff
Multi-value paramsAccepts vectors (c(1,2)) or colon-separated strings ("1:2")
Functions14 (7 PT + 7 EN)

SIORG — Organizational Structure

https://estruturaorganizacional.dados.gov.br/

Federal organizational structure: ministries, autarchies, foundations, and their internal hierarchy. Used as a dictionary to look up SIORG codes for CUSTOS API queries.

DetailValue
PaginationNone (single response, JSON-based)
Retries5 attempts, progressive backoff
Functions6 (3 PT + 3 EN)

SIOPE — Education Spending

https://www.fnde.gov.br/olinda-ide/servico/DADOS_ABERTOS_SIOPE/versao/v1/odata/

Education spending data from FNDE/MEC: revenues, expenses, indicators, staff compensation, and declaration officials. Uses an OData-style API.

DetailValue
PaginationOData ($top/$skip), automatic
Default page size1,000 rows
Retries5 attempts, progressive backoff
max_rowsSupported
filterOData $filter for server-side filtering (e.g., "NOM_MUNI eq 'Recife'")
orderbyOData $orderby for server-side sorting
selectOData $select to choose specific columns
Functions16 (8 PT + 8 EN)

Tip: Use filter to narrow results on the server before downloading. Column names in filter/select/orderby must use the original API names (uppercase). Run a max_rows = 1 query and toupper(names(result)) to discover valid column names.

Common features (all APIs)

FeatureDetails
CachingIn-memory per session. Clear with tesouror_clear_cache().
Retries5 attempts with progressive backoff (3s, 6s, 9s, 12s, 15s) on HTTP 500/502/503/504/429 and connection failures. HTTP 400/404 are not retried.
verbose modePer-call (verbose = TRUE) or global (options(tesouror.verbose = TRUE)). Prints full API URL for every request.
Column cleaningjanitor::clean_names() applied to all responses (consistent snake_case).
BilingualEvery function has Portuguese (API-native) and English-named aliases.
OutputTidy tibbles with whitespace trimming.
Error messagesFriendly, actionable messages with URL and hints. HTTP 400 errors suggest checking column names.

License

MIT

Copy Link

Version

Install

install.packages('tesouror')

Version

0.2.2

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Andre Leite

Last Published

May 6th, 2026

Functions in tesouror (0.2.2)

get_msc_controle

Get MSC control accounts data
get_res_cdp

Get debt capacity result (CDP)
get_extrato

Get delivery status extract
get_opc_cronograma_liberacoes

Get credit operation release schedule
get_pvl_tramitacao

Get PVL processing status (approved non-credit operations)
get_siope_indicadores

Get SIOPE education indicators
get_siope_despesas_funcao

Get SIOPE expenses by education function
get_rreo

Get Budget Execution Summary Report data (RREO)
get_rgf_for_state

Get RGF data for all municipalities of a Brazilian state
get_opc_cronograma_pagamentos

Get credit operation payment schedule
get_rreo_for_state

Get RREO data for all municipalities of a Brazilian state
get_siope_dados_gerais

Get SIOPE general data
get_tc_por_estados_detalhe

Get detailed constitutional transfers by state
get_tc_por_estados

Get constitutional transfers by state
get_siorg_estrutura

Get organizational structure from SIORG
get_siope_responsaveis

Get SIOPE officials/responsible persons data
tesouror_clear_cache

Clear the tesouror in-memory cache
tidy_rreo

Tidy a RREO tibble by topic, reconciling layout drift across years
get_tc_municipios

Get municipality dictionary
get_tc_estados

Get state dictionary
get_rgf

Get Fiscal Management Report data (RGF)
get_res_cronograma_pagamentos

Get debt payment schedule result
get_tc_transferencias

Get transfer type dictionary
rreo_layout

Return the bundled RREO layout reference table
get_siope_despesas

Get SIOPE education expenses data
get_siorg_orgaos

Get federal organizations from SIORG
get_siope_info_complementares

Get SIOPE supplementary information
get_tc_por_municipio_detalhe

Get detailed constitutional transfers by municipality
get_tc_por_municipio

Get constitutional transfers by municipality
get_siorg_unidade

Get details of a single SIORG unit
rreo_normalize_columns

Normalize the coluna field of a RREO tibble across years
get_siope_receitas

Get SIOPE education revenue data
get_siope_remuneracao

Get SIOPE staff compensation data
tesouror-package

tesouror: Access Brazilian National Treasury Open Data APIs
get_dca

Get annual accounts data (DCA)
get_entes

Get list of Brazilian government entities
get_custos_pensionistas

Get pensioner cost data
get_custos_pessoal_inativo

Get retired staff cost data
get_anexos

Get report appendix reference table
get_custos_demais

Get other cost data
get_custos_transferencias

Get transfer cost data
get_custos_pessoal_ativo

Get active staff cost data
get_custos_depreciacao

Get depreciation cost data
get_dca_for_state

Get DCA data for all municipalities of a Brazilian state
get_msc_orcamentaria

Get MSC budgetary accounts data
get_pvl

Get public debt verification requests (PVL)
get_msc_patrimonial

Get MSC equity/asset accounts data
get_opc_taxa_cambio

Get credit operation exchange rate data