Skip to content

🇧🇷 Minimalist and easy-to-use Python library designed to query CEP (Postal Address Code) data.

License

mstuttgart/brazilcep

Repository files navigation

BrazilCEP Logo
BrazilCEP

A minimalist and easy-to-use Python library for querying Brazilian CEP (Postal Address Code) data

GitHub Workflow Status Codecov Read the Docs Downloads PyPI Version Python Versions License

FeaturesInstallationQuick StartUsage ExamplesDocumentationContributingLicense


Features

Simple and Intuitive API - Easy-to-use interface for CEP queries

🚀 Async/Await Support - Full support for asynchronous operations

🔄 Multiple Web Services - Support for ViaCEP, ApiCEP, and OpenCEP

Fast and Lightweight - Minimal dependencies and optimized performance

🛡️ Type Hints - Full type annotation support for better IDE experience

🔧 Customizable - Configure timeout, proxies, and preferred web service

📦 Well Tested - Comprehensive test coverage

Installation

BrazilCEP requires Python 3.9 or higher.

Install using pip:

pip install brazilcep

Or using poetry:

poetry add brazilcep

Quick Start

Synchronous Usage

import brazilcep

# Query a CEP
address = brazilcep.get_address_from_cep('37503-130')

print(address)
# Output:
# {
#     'cep': '37503-130',
#     'street': 'Rua Geraldino Campista',
#     'district': 'Santo Antônio',
#     'city': 'Itajubá',
#     'uf': 'MG',
#     'complement': 'até 214/215'
# }

Asynchronous Usage

import asyncio
import brazilcep

async def main():
    address = await brazilcep.async_get_address_from_cep('37503-130')
    print(address)

asyncio.run(main())

Usage Examples

Choosing a Web Service

BrazilCEP supports multiple CEP lookup services. You can specify which one to use:

from brazilcep import get_address_from_cep, WebService

# Using ViaCEP (default for backwards compatibility, but OpenCEP is now default)
address = get_address_from_cep('37503-130', webservice=WebService.VIACEP)

# Using ApiCEP
address = get_address_from_cep('37503-130', webservice=WebService.APICEP)

# Using OpenCEP (default)
address = get_address_from_cep('37503-130', webservice=WebService.OPENCEP)

Configuring Timeout

Set a custom timeout for requests (default is 5 seconds):

# Set timeout to 10 seconds
address = get_address_from_cep('37503-130', timeout=10)

Using Proxies

Configure proxy settings for requests:

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080',
}

address = get_address_from_cep('37503-130', proxies=proxies)

Handling Exceptions

from brazilcep import get_address_from_cep, exceptions

try:
    address = get_address_from_cep('00000-000')
except exceptions.CEPNotFound:
    print('CEP not found!')
except exceptions.InvalidCEP:
    print('Invalid CEP format!')
except exceptions.ConnectionError:
    print('Connection error!')
except exceptions.Timeout:
    print('Request timeout!')
except exceptions.BrazilCEPException as e:
    print(f'An error occurred: {e}')

Complete Async Example

import asyncio
from brazilcep import async_get_address_from_cep, WebService, exceptions

async def fetch_multiple_ceps():
    """Fetch multiple CEPs concurrently."""
    ceps = ['37503-130', '01310-100', '20040-020']

    tasks = [
        async_get_address_from_cep(cep, webservice=WebService.OPENCEP)
        for cep in ceps
    ]

    try:
        addresses = await asyncio.gather(*tasks)
        for cep, address in zip(ceps, addresses):
            print(f"\nCEP {cep}:")
            print(f"  Street: {address['street']}")
            print(f"  City: {address['city']}/{address['uf']}")
    except exceptions.BrazilCEPException as e:
        print(f"Error fetching addresses: {e}")

asyncio.run(fetch_multiple_ceps())

Supported Web Services

Service Website Status Rate Limit
OpenCEP https://opencep.com ✅ Active Yes
ViaCEP https://viacep.com.br ✅ Active Yes
ApiCEP https://apicep.com ✅ Active Yes

Important

BrazilCEP does not guarantee the availability or support of any third-party query APIs. This library serves as a convenient interface for accessing these services. Please check each service's terms of use and rate limits.

Response Format

All queries return a dictionary with the following structure:

{
    'cep': str,        # Postal code (e.g., '37503-130')
    'street': str,     # Street name (e.g., 'Rua Geraldino Campista')
    'district': str,   # Neighborhood/district (e.g., 'Santo Antônio')
    'city': str,       # City name (e.g., 'Itajubá')
    'uf': str,         # State abbreviation (e.g., 'MG')
    'complement': str  # Additional information (may be empty)
}

Documentation

For comprehensive documentation, including advanced usage, API reference, and migration guides, visit:

📚 BrazilCEP Documentation

Quick Links

Contributing

Contributions are welcome! Here's how you can help:

  1. 🐛 Report bugs - Open an issue describing the bug
  2. 💡 Suggest features - Share your ideas for improvements
  3. 📝 Improve documentation - Help make the docs clearer
  4. 🔧 Submit pull requests - Fix bugs or add features

Please read our Contributing Guide before submitting a pull request.

Development Setup

# Clone the repository
git clone https://github.com/mstuttgart/brazilcep.git
cd brazilcep

# Install dependencies
make setup

# Run tests
make test

# Run linting
make lint

# Run all checks
make check

About CEP

CEP (Código de Endereçamento Postal) or Postal Address Code is the Brazilian postal code system created, maintained, and organized by Correios do Brasil (Brazilian Post Office). It consists of eight digits and helps streamline address organization and delivery of mail and packages across Brazil.

Migration from PyCEPCorreios

BrazilCEP is the successor to PyCEPCorreios. To migrate your code:

Old (PyCEPCorreios):

from pycepcorreios import get_address_from_cep

New (BrazilCEP):

from brazilcep import get_address_from_cep

For detailed migration instructions, see the migration guide.

License

BrazilCEP is released under the MIT License.

Credits

Created and maintained by Michell Stuttgart.

Support


Made with ❤️ in Brazil

About

🇧🇷 Minimalist and easy-to-use Python library designed to query CEP (Postal Address Code) data.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

Contributors 17