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.
Choosing and ordering
Section titled “Choosing and ordering”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()],});Configuring a provider
Section titled “Configuring a provider”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 }).
Writing your own provider
Section titled “Writing your own provider”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
providerfield; unicep fills it in with thename. - Throw
CepNotFoundErrorwhen the CEP does not exist and another error (preferablyProviderError) for service failures. Only failures count against the circuit breaker. - Pass the
signaltofetch, so timeouts and cancellation work. - The
namemust be unique within the instance.
Using them responsibly
Section titled “Using them responsibly”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.