Skip to content

Providers

A provider is the adapter for one CEP service. unicep ships four, all of them work straight from the browser (the services allow CORS) and return the same Address.

Function Service Has complement Has ibgeCode
viaCep() ViaCEP yes yes
brasilApi() BrasilAPI (CEP v2) no yes
openCep() OpenCEP yes yes
awesomeApi() AwesomeAPI no yes

defaultProviders() returns all four, in that order.

The order of the list is the priority. Pass only the ones you want, in the order you prefer:

import { Unicep, brasilApi, openCep, viaCep } from '@unicep/core';
const unicep = new Unicep({
providers: [brasilApi(), viaCep(), openCep()],
});

All built-in providers accept the same options:

Option What it does
fetch Your own fetch implementation (default: globalThis.fetch). Useful for tests and proxies.
baseUrl Changes the service address, to use a proxy or your own instance.
import { Unicep, brasilApi, viaCep } from '@unicep/core';
const unicep = new Unicep({
providers: [
viaCep({ baseUrl: 'https://my-proxy.example.com/viacep' }),
brasilApi({ fetch: myFetch }),
],
});

To apply the same options to all of them at once: defaultProviders({ fetch: myFetch }).

To use a service unicep does not have, implement the CepProvider interface:

import { CepNotFoundError, ProviderError, type CepProvider } from '@unicep/core';
const myProvider: CepProvider = {
name: 'my-api',
async lookup(cep, { signal }) {
const response = await fetch(`https://my-api.example.com/cep/${cep}`, { signal });
if (response.status === 404) throw new CepNotFoundError(cep);
if (!response.ok) throw new ProviderError('my-api', `HTTP ${response.status}`);
const data = await response.json();
return {
cep,
street: data.street,
neighborhood: data.district,
city: data.city,
state: data.uf,
};
},
};

Rules:

  • Return the address without the provider field; unicep fills it in with the name.
  • Throw CepNotFoundError when the CEP does not exist and another error (preferably ProviderError) for service failures. Only failures count against the circuit breaker.
  • Pass the signal to fetch, so timeouts and cancellation work.
  • The name must be unique within the instance.

unicep does not provide, host or own any CEP data or API. It only queries independent public services, each with its own terms, limits and availability, and it is not affiliated with any of them.