PHPackages                             zanchi/viacep - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. zanchi/viacep

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

zanchi/viacep
=============

CEP search Brazilian utilizes

01PHP

Since Aug 15Pushed 9mo agoCompare

[ Source](https://github.com/luiszanchi/viacep)[ Packagist](https://packagist.org/packages/zanchi/viacep)[ RSS](/packages/zanchi-viacep/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

ViaCEP PHP (Zanchi\\ViaCep)
===========================

[](#viacep-php-zanchiviacep)

Simple utilities to consume the public ViaCEP API ().

This package exposes two main services to query addresses and two DTOs to represent the returned data.

- Services:
    - Zanchi\\ViaCep\\Service\\ViaCepGetByCepService
    - Zanchi\\ViaCep\\Service\\ViaCepGetBySearchService
- DTOs:
    - Zanchi\\ViaCep\\Dtos\\CepDto
    - Zanchi\\ViaCep\\Dtos\\ViaCepDto and Zanchi\\ViaCep\\Dtos\\ViaCepArray (collection)

Requirements
------------

[](#requirements)

- PHP ^7.4
- Extensions: ext-json, ext-curl

When installed via Composer, PSR-4 autoload is already configured (root namespace: `Zanchi\\ViaCep\\`).

How it works (overview)
-----------------------

[](#how-it-works-overview)

- ViaCepGetByCepService: queries a single CEP (e.g., 01001-000) and returns a ViaCepDto or null if not found.
- ViaCepGetBySearchService: searches by UF (state) + city + street and returns a ViaCepArray collection with 0..N results (each one is a ViaCepDto).
- CepDto: encapsulates a CEP with formatting helpers (with/without hyphen). The value is sanitized to keep only digits.

Relevant exceptions:

- Zanchi\\ViaCep\\Exceptions\\ViaCepRequestInvalidException: problems during the HTTP request or JSON parsing.
- \\InvalidArgumentException: input validations (e.g., invalid UF, too-short strings, wrong parameter type).

Service: ViaCepGetByCepService
------------------------------

[](#service-viacepgetbycepservice)

Namespace: `Zanchi\\ViaCep\\Service\\ViaCepGetByCepService`

Main signature:

- `public function execute(CepDto|string $cepDto): ?ViaCepDto`

Rules/validation:

- Accepts a `CepDto` or a `string` with the CEP.
- If a `string` is provided, a `CepDto` instance is created internally (the string is sanitized to contain digits only).
- On HTTP/JSON error, `ViaCepRequestInvalidException` will be thrown.

Return value:

- `ViaCepDto` when the CEP is found.
- `null` when the API returns an empty result (not found).

Usage example:

```
use Zanchi\ViaCep\Service\ViaCepGetByCepService;
use Zanchi\ViaCep\Dtos\CepDto;

$service = new ViaCepGetByCepService();

// Option 1: passing a string
$dto = $service->execute('01001-000');

// Option 2: passing a CepDto
//$dto = $service->execute(new CepDto('01001000'));

if ($dto !== null) {
    echo $dto->logradouro . PHP_EOL;           // Praça da Sé
    echo $dto->bairro . PHP_EOL;               // Sé
    echo $dto->localidade . ' - ' . $dto->uf;  // São Paulo - SP
}
```

Service: ViaCepGetBySearchService
---------------------------------

[](#service-viacepgetbysearchservice)

Namespace: `Zanchi\\ViaCep\\Service\\ViaCepGetBySearchService`

Main signature:

- `public function execute(string $uf, string $cidade, string $logradouro): ViaCepArray`

Rules/validation:

- `uf` must have exactly 2 characters; it is converted to uppercase.
- `cidade` (city) must have at least 3 characters; spaces are encoded as `%20`.
- `logradouro` (street) must have at least 3 characters; spaces are replaced with `+`.
- On HTTP/JSON error, `ViaCepRequestInvalidException` will be thrown.

Return value:

- `ViaCepArray`, a collection (Countable, ArrayAccess, JsonSerializable) containing `ViaCepDto`.

Usage example:

```
use Zanchi\ViaCep\Service\ViaCepGetBySearchService;

$service = new ViaCepGetBySearchService();
$results = $service->execute('SP', 'São Paulo', 'Praça da Sé');

echo 'Total: ' . count($results) . PHP_EOL;

foreach ($results->all() as $item) { // $item is a ViaCepDto
    echo $item->logradouro . ' - ' . $item->bairro . ' - ' . $item->localidade . '/' . $item->uf . PHP_EOL;
}

// You can also access by index:
//$first = $results[0] ?? null;
```

DTO: CepDto
-----------

[](#dto-cepdto)

Namespace: `Zanchi\\ViaCep\\Dtos\\CepDto`

Responsibility:

- Encapsulate a CEP and provide formatting helpers.

Important behavior:

- The constructor sanitizes the input, keeping digits only (removes dots, hyphen, spaces, etc.).
- Methods:
    - `unformatted(): string` — returns the 8 digits only (e.g., "01001000").
    - `formatted(): string` — returns the standard format with hyphen (e.g., "01001-000").

Note:

- The class contains an internal length validation routine (8 digits), but the explicit check is not invoked externally. When using the services, if the CEP is invalid, the API may simply return no result.

Quick example:

```
use Zanchi\ViaCep\Dtos\CepDto;

$cep = new CepDto('01001-000');
echo $cep->unformatted(); // 01001000
echo $cep->formatted();   // 01001-000
```

DTOs: ViaCepDto and ViaCepArray
-------------------------------

[](#dtos-viacepdto-and-viaceparray)

- `ViaCepDto` represents the payload of an address returned by the ViaCEP API. Typical fields: `cep` (as CepDto), `logradouro`, `bairro`, `localidade`, `uf`, `ibge`, etc.
    - Factories: `ViaCepDto::fromArray(array $data)`, `ViaCepDto::fromJson(string $json)`.
    - Serialization: `toArray()` and `jsonSerialize()`.
- `ViaCepArray` is a collection of `ViaCepDto`.
    - Factory: `ViaCepArray::fromArray(array $data)` (usually the array returned by the API when searching by street).
    - Methods: `count()`, `all()`, index access (`$list[0]`), and `jsonSerialize()`.

Error handling
--------------

[](#error-handling)

- Network failures, non-2xx HTTP responses or invalid JSON: `Zanchi\ViaCep\Exceptions\ViaCepRequestInvalidException`.
- Invalid parameters (e.g., UF with wrong size, wrong types, too-short strings): `\InvalidArgumentException`.

Suggestion: wrap calls in try/catch to handle expected errors:

```
use Zanchi\ViaCep\Service\ViaCepGetByCepService;
use Zanchi\ViaCep\Exceptions\ViaCepRequestInvalidException;

$service = new ViaCepGetByCepService();

try {
    $dto = $service->execute('01001-000');
} catch (ViaCepRequestInvalidException $e) {
    // Handle request/JSON errors
} catch (\InvalidArgumentException $e) {
    // Handle input validations
}
```

Running tests
-------------

[](#running-tests)

This repository includes sample tests (folder `tests/`). Adjust environment and connectivity as needed to run real calls to ViaCEP.

License
-------

[](#license)

MIT

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance41

Moderate activity, may be stable

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/c9374780eacaa7f04120ca30f67c74f913d4ba120c52d9b75858255ed6b41906?d=identicon)[zanchi](/maintainers/zanchi)

---

Top Contributors

[![luiszanchi](https://avatars.githubusercontent.com/u/26325408?v=4)](https://github.com/luiszanchi "luiszanchi (2 commits)")

### Embed Badge

![Health badge](/badges/zanchi-viacep/health.svg)

```
[![Health](https://phpackages.com/badges/zanchi-viacep/health.svg)](https://phpackages.com/packages/zanchi-viacep)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
