npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

brasilapi-sdk

v2.0.0

Published

TypeScript SDK for Brasil API - Query Brazilian postal codes (CEP), companies (CNPJ), banks, FIPE vehicle prices, IBGE data, holidays, and more

Readme

Brasil API Banner

BrasilAPI SDK

TypeScript SDK for Brasil API - Access Brazilian data with type safety and modern features

npm version npm downloads CI License: MIT TypeScript Node.js Version

FeaturesInstallationQuick StartDocumentationContributing


🚀 Features

A modern, production-ready TypeScript SDK for Brasil API with comprehensive coverage of all 33 endpoints:

  • 100% TypeScript - Full type safety with comprehensive type definitions
  • 🔄 Automatic Retries - Smart retry logic with exponential backoff
  • 🛡️ Error Handling - Custom error types for better error management
  • 📦 Zero Dependencies - Uses native Node.js fetch (Node 18+)
  • 🌳 Tree-Shakeable - Optimized ESM and CommonJS builds
  • 🧪 100% Tested - Comprehensive test coverage with Jest
  • 🚀 Modern - Built with latest TypeScript and modern tooling
  • 📚 Well Documented - Extensive examples and API reference

📡 All Brasil API Endpoints (33/33)

  • getCep(cep) - Search CEP with multiple providers
  • getCepV2(cep) - CEP with geolocation data
  • getCnpj(cnpj) - Complete company information
  • getBanks() - List all Brazilian banks
  • getBankByCode(code) - Get bank by code
  • getDDD(ddd) - Get state and cities by area code
  • getFeriadosByAno(year) - Get holidays for specific year
  • getTabelaFipe() - List reference tables
  • getMarcas(type) - List vehicle brands
  • getVeiculos(type, brandCode) - List vehicles
  • getPrecoVeiculo(fipeCode) - Get vehicle price
  • getEstados() - List all Brazilian states
  • getEstadoBySigla(uf) - Get state by abbreviation
  • getMunicipios(uf) - Get municipalities by state
  • getMoedas() - List available currencies
  • getCotacao(currency, date) - Get exchange rate for date
  • getCorretoras() - List all brokers
  • getCorretoraByCode(cnpj) - Get broker by CNPJ
  • getCidades() - List all cities
  • buscarCidade(name) - Search city by name
  • getClimaCapitais() - Current weather in capitals
  • getClimaAeroporto(icao) - Airport weather
  • getPrevisaoCidade(code, days) - Weather forecast
  • getPrevisaoOceano(code, days) - Ocean forecast
  • getIsbn(isbn) - Get book details by ISBN
  • getNcm(code) - Get NCM by code
  • searchNcm(query) - Search NCM
  • getAllNcm() - List all NCM codes
  • getParticipantes() - List all PIX participants
  • getDomainStatus(domain) - Check .br domain status
  • getTaxa(acronym) - Get specific rate
  • getAllTaxas() - List all rates

📦 Installation

npm install brasilapi-sdk

Requirements: Node.js >= 18.0.0 (for native fetch support)


🎯 Quick Start

import BrasilAPI from 'brasilapi-sdk';

// Query a postal code
const address = await BrasilAPI.cep().getCep('05010-000');
console.log(address.city); // "São Paulo"

// Get company information
const company = await BrasilAPI.cnpj().getCnpj('19.131.243/0001-97');
console.log(company.razao_social); // "OPEN KNOWLEDGE BRASIL"

// Get national holidays
const holidays = await BrasilAPI.feriados().getFeriadosByAno(2024);
console.log(holidays[0].name); // "Confraternização mundial"

📚 Documentation

CEP (Postal Code)

Query Brazilian postal codes with automatic fallback between providers.

import { cep } from 'brasilapi-sdk';

// Basic CEP lookup
const result = await cep().getCep('05010-000');
console.log(result);
// {
//   cep: "05010000",
//   state: "SP",
//   city: "São Paulo",
//   neighborhood: "Perdizes",
//   street: "Rua Caiubi"
// }

// CEP V2 with geolocation
const resultV2 = await cep().getCepV2('05010000');
console.log(resultV2.location);
// {
//   type: "Point",
//   coordinates: {
//     longitude: "-46.6753",
//     latitude: "-23.5358"
//   }
// }

CNPJ (Company Registry)

Get complete company information from Receita Federal.

import { cnpj } from 'brasilapi-sdk';

const company = await cnpj().getCnpj('19.131.243/0001-97');

console.log(company.razao_social); // Company name
console.log(company.qsa); // Partners/shareholders
console.log(company.cnaes_secundarios); // Secondary activities

Banks

List all Brazilian banks or get specific bank information.

import { banks } from 'brasilapi-sdk';

// List all banks
const allBanks = await banks().getBanks();

// Get specific bank
const bb = await banks().getBankByCode(1);
console.log(bb.fullName); // "Banco do Brasil S.A."

DDD (Area Code)

import { ddd } from 'brasilapi-sdk';

const info = await ddd().getDDD(11);
console.log(info.state); // "SP"
console.log(info.cities); // ["São Paulo", "Guarulhos", ...]

National Holidays

import { feriados } from 'brasilapi-sdk';

const holidays = await feriados().getFeriadosByAno(2024);

holidays.forEach(holiday => {
  console.log(`${holiday.date}: ${holiday.name}`);
});

FIPE (Vehicle Prices)

import { fipe } from 'brasilapi-sdk';

const fipeModule = fipe();

// List reference tables
const tables = await fipeModule.getTabelaFipe();

// List car brands
const brands = await fipeModule.getMarcas('carros');

// List vehicles for a brand
const vehicles = await fipeModule.getVeiculos('carros', 59);

// Get vehicle price
const prices = await fipeModule.getPrecoVeiculo('001004-9');
console.log(prices[0].valor); // "R$ 6.022,00"

IBGE (Geographic Data)

import { ibge } from 'brasilapi-sdk';

const ibgeModule = ibge();

// List all states
const states = await ibgeModule.getEstados();

// Get specific state
const sp = await ibgeModule.getEstadoBySigla('SP');

// List municipalities
const cities = await ibgeModule.getMunicipios('SP');

Currency Exchange

import { cambio } from 'brasilapi-sdk';

const cambioModule = cambio();

// List available currencies
const currencies = await cambioModule.getMoedas();

// Get exchange rate
const rate = await cambioModule.getCotacao('USD', '2024-03-07');
console.log(rate.cotacoes[0].cotacao_compra); // 5.7702

Stock Brokers

import { corretoras } from 'brasilapi-sdk';

const corretorasModule = corretoras();

// List all brokers
const all = await corretorasModule.getCorretoras();

// Get specific broker
const xp = await corretorasModule.getCorretoraByCode('02332886000104');

Weather (CPTEC)

import { cptec } from 'brasilapi-sdk';

const cptecModule = cptec();

// Search cities
const cities = await cptecModule.buscarCidade('São Paulo');

// Current weather in capitals
const capitals = await cptecModule.getClimaCapitais();

// Airport weather
const airport = await cptecModule.getClimaAeroporto('SBGR');

// Weather forecast (up to 6 days)
const forecast = await cptecModule.getPrevisaoCidade(244, 6);

// Ocean forecast
const ocean = await cptecModule.getPrevisaoOceano(241, 3);

Book Information (ISBN)

import { isbn } from 'brasilapi-sdk';

const book = await isbn().getIsbn('9788545702870');

console.log(book.title); // Book title
console.log(book.authors); // Authors array
console.log(book.publisher); // Publisher name

NCM Codes

import { ncm } from 'brasilapi-sdk';

const ncmModule = ncm();

// Get specific NCM
const code = await ncmModule.getNcm('01012100');

// Search NCM
const results = await ncmModule.searchNcm('café');

// List all NCM codes
const all = await ncmModule.getAllNcm();

PIX Participants

import { pix } from 'brasilapi-sdk';

const participants = await pix().getParticipantes();

Domain Status (.br)

import { registroBr } from 'brasilapi-sdk';

const domain = await registroBr().getDomainStatus('google.com.br');
console.log(domain.status); // Domain status

Interest Rates

import { taxas } from 'brasilapi-sdk';

const taxasModule = taxas();

// Get specific rate
const selic = await taxasModule.getTaxa('selic');

// List all rates
const all = await taxasModule.getAllTaxas();

🔧 Error Handling

The SDK provides custom error types for better error management:

import { 
  cep, 
  NotFoundError, 
  ValidationError, 
  NetworkError 
} from 'brasilapi-sdk';

try {
  const result = await cep().getCep('00000000');
} catch (error) {
  if (error instanceof NotFoundError) {
    console.error('❌ CEP not found');
  } else if (error instanceof ValidationError) {
    console.error('❌ Invalid CEP format');
  } else if (error instanceof NetworkError) {
    console.error('❌ Network error occurred');
  } else {
    console.error('❌ Unexpected error:', error);
  }
}

Available Error Types

| Error Type | Description | HTTP Status | |------------|-------------|-------------| | BrasilAPIError | Base error class | Any | | NotFoundError | Resource not found | 404 | | ValidationError | Invalid request parameters | 400 | | NetworkError | Network connectivity issues | - |


⚙️ Advanced Configuration

The SDK uses automatic retry logic with exponential backoff:

import { BrasilAPIClient } from 'brasilapi-sdk';

const client = new BrasilAPIClient();

// Customize retry behavior
const data = await client.get('/cep/v1/05010000', {
  retries: 5,        // Number of retries (default: 3)
  retryDelay: 2000   // Initial delay in ms (default: 1000)
});

🧪 Testing

# Run all tests
npm test

# Run tests with coverage
npm run coverage

# Run tests in watch mode
npm run test:watch

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Run tests (npm test)
  4. Commit your changes (git commit -m 'Add some AmazingFeature')
  5. Push to the branch (git push origin feature/AmazingFeature)
  6. Open a Pull Request

See CONTRIBUTING.md for detailed guidelines.


📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • Brasil API - The amazing free API that makes this SDK possible
  • All contributors who have helped improve this package

🔗 Links


📊 Package Stats

npm bundle size npm type definitions GitHub last commit GitHub stars


Made with ❤️ by guhcostan

If this project helped you, consider giving it a ⭐️