How to find a postal address in the Post Office?

Posted on

Question :

How do I search the post office for the details of an address using your zip code (similar to the address records we see on e-commerce sites)?

    

Answer :

The post office offers this information through the e-DNE (National Address Book).

  

In 2000, the Post Office launched the National Directory of Addresses (DNE), a database containing the CEP of all Brazil and elements of address (description of streets, neighborhoods, municipalities, towns, villages).

p>
  
  

In 2012, the Post Office innovated the DNE and launched the e-DNE, which was purchased in a few minutes via the Internet in the Post Office virtual store by download. Today your purchase no longer requires formalization of contract, it is only made through adherence to the Term of Commitment.

( font )

The e-DNE is a downloadable database in text (.txt) and MS-Access (.mdb) formats.

This database is paid, including your updates . You can purchase at Online Store (prices range from around $ 220 to $ 2,500).

Unfortunately this is the only form available by the Post Office access to your ZIP code base; a webservice would be more efficient ( for other services they provide ).

    

You can use the Postmon API.

They use an online database of Post Office Postcodes for searches that are not yet locally cached in Postmon.

For example, you can get JSON address information from a zip code using the API:

http://api.postmon.com.br/v1/cep/*cep_a_consultar*

In addition the Postmon code is open and available at Github .

    

I think it’s even easier to have everyone listed, even more so that there are some repeated in different responses.

And if you know anything else to have in the list you will be welcome, just edit !

    

In C # using webservice link as pointed out by our colleague @ talles looks like it has not been updated in quite a while, I was able to quickly do a few lines of code :

string cep = "01010-010"; // Contém o CEP que será pesquisado
// Objeto DataSet que receberá a tabela em XML que contém os dados da pesquisa
DataSet ds = new DataSet();
// Armazena o arquivo XML retirado da página onde o CEP foi pesquisado
ds.ReadXml("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep);
// Caso tenha encontrado o CEP o valor da primeira célula da primeira linha da tabela será 1 
if (ds.Tables[0].Rows[0][0].ToString() == "1")
{
    // Repassa os valores contidos nas células da primeira linha para suas
    // respectivas TextBox'es, para serem exibidos para o usuário
    textBoxUf.Text = ds.Tables[0].Rows[0]["uf"].ToString().Trim();
    textBoxCidade.Text = ds.Tables[0].Rows[0]["cidade"].ToString().Trim();
    textBoxBairro.Text = ds.Tables[0].Rows[0]["bairro"].ToString().Trim();
    textBoxTipoLogradouro.Text =
        ds.Tables[0].Rows[0]["tipo_logradouro"].ToString().Trim();
    textBoxEnd.Text = ds.Tables[0].Rows[0]["logradouro"].ToString().Trim();
    textBoxStatus.Text = "CEP completo";
}
else
{
    MessageBox.Show("CEP não encontrado.");
}

    

Using the post office itself, using PHP, using DOM + XPath:

function buscaCEP($cep)
{
    $response = file_get_contents(
        'http://m.correios.com.br/movel/buscaCepConfirma.do',
        false,
        stream_context_create([
            'http' => [
                'header' => "Content-Type: application/x-www-form-urlencodedrn",
                'method' => 'POST',
                'content' => http_build_query([
                    'cepEntrada' => $cep,
                    'metodo' => 'buscarCep',
                ]),
            ],
        ])
    );

    $dom = new DOMDocument();
    @$dom->loadHTML($response);
    $xpath = new DOMXPath($dom);
    $values = $xpath->query('//*[@class="respostadestaque"]');
    $result = [];

    // Se não encontrar CEP, retorna false
    if (!$values->length) {
        return false;
    }

    // Obtém informações desejadas, tratando-as quando necessário
    foreach ($values as $value) {
        $result[] = preg_replace(
            '~[s]{2,}~',
            '',
            trim($value->childNodes->item(0)->nodeValue)
        );
    }

    if ($values->length > 2) {
        // CEPs de logradouros
        list($logradouro, $bairro, $localidade, $cep) = $result;
    } else {
        // CEPs de localidades
        list($logradouro, $bairro) = null;
        list($localidade, $cep) = $result;
    }

    list($localidade, $uf) = explode('/', $localidade);

    return compact('logradouro', 'bairro', 'localidade', 'uf', 'cep');
}

    

boy, have the webservice of the virtual republic, take a look at it, if you look for address data by zip code, just use a javascript that they provide there, I’ve already used it on a mine site and it works which is a marvel.
link

    

In this example, I’m using javascript and browsing the webservice of the Virtual Republic.

I look for the address in this API using the zip code, and I fill in the fields type of public place , neighborhood , city and uf with the information received.

<script type="text/javascript">


$(document).ready(function(){
    $("#cep").blur(function(e){
        if($.trim($("#cep").val()) != ""){
            $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
                if(resultadoCEP["resultado"]){
                    $("#rua").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
                    $("#bairro").val(unescape(resultadoCEP["bairro"]));
                    $("#cidade").val(unescape(resultadoCEP["cidade"]));
                    $("#estado").val(unescape(resultadoCEP["uf"]));
                }else{
                    alert("Não foi possivel encontrar o endereço");
                }
            });             
        }
    })
});
</script>

    

There is a very simple way

function getEndereco() {

    if ($.trim($("#cep").val()) !== "") {
        $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=" + $("#cep").val(), function() {

            if (resultadoCEP["resultado"]) {
                $("#rua").val(unescape(resultadoCEP["tipo_logradouro"]) + " " + unescape(resultadoCEP["logradouro"]));
                $("#bairro").val(unescape(resultadoCEP["bairro"]));
                $("#cidade").val(unescape(resultadoCEP["cidade"]));
                $("#estado").val(unescape(resultadoCEP["uf"]));
                $("#pais").val('Brasil');
                $("#numero").focus();
            }
        });
    }

}

It returns a Json and you just need to add the fields where needed.

    

An alternative is the Open CEP : “[…] a project that aims to provide free access and collaboratively build a data with geolocated postal codes (ZIP codes) of all Brazil. “.

The database has 917952 zip codes, most of which are geolocated, i.e., have latitude and longitude. Geolocation is not always accurate, so it’s worth helping the project.

To use the API you need to register for free and you will receive a unique token. And internally there is an interface with simple graphics showing your use of the API.

An example of how to use the Open Python zip API:

from urllib2 import urlopen, Request
url = "http://www.cepaberto.com/api/v1/ceps.json?cep=40010000"
headers = {'Authorization': 'Token token=SEU_TOKEN_PESSOAL_AQUI'}
json = urlopen(Request(url, None, headers=headers)).read()
print json
{"altitude":8, "bairro":"Comércio", "cep":"40010000", "cidade":"Salvador", "ddd":71, "ibge":"2927408", "latitude":"-12.971", "logradouro":"Avenida da Franca", "longitude":"-38.511"}

    

Leave a Reply

Your email address will not be published. Required fields are marked *