📭 API para acesso as informações dos CEPs do Brasil https://brcep-dlfeappmhe.now.sh
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
img
vendor
.env.example
.gitignore
.travis.yml
Dockerfile
LICENSE
Makefile
Procfile
README.md
app.json
cepaberto.go
server.go
server_test.go
util.go
viacep.go

README.md

brcep

build status Go Report Card github closed issues codecov

API para acesso a informações dos CEPs do Brasil. A ideia central é não ficar dependente de uma API específica, e sim, ter a facilidade de acessar a brcep e ela se encarrega em consultar diversas fontes e lhe devolver as informações do CEP de forma rápida e fácil.

O projeto brcep faz consultas às APIs ViaCEP e CEPAberto.

brcep

Tópicos

Acesso a API

Heroku

Para visualizar os dados acesse https://brcep-dlfeappmhe.now.sh/78048000/json.

Zeit Now

Para visualizar os dados acesse https://brcep-qnlohrjtbl.now.sh/78048000/json.

Response

{
  "cep": "78048000",
  "endereco": "Avenida Miguel Sutil, de 5799/5800 a 7887/7888",
  "bairro": "Consil",
  "complemento": "",
  "cidade": "Cuiabá",
  "uf": "MT",
  "latitude": "-15.5786867",
  "longitude": "-56.0952081",
  "ddd": "",
  "unidade": "",
  "ibge": "5103403"
}
  • O campo "CEP" retorna somente números.
  • Os campos "complemento", "latitude" e "longitude" podem retornar em branco dependendo da API consultada.
  • Os demais campos sempre retornarão valores.

Exemplos

curl

curl https://brcep-dlfeappmhe.now.sh/78048000/json

Javascript

var request = require('request');
var options = {
    url: 'https://brcep-dlfeappmhe.now.sh/78048000/json',
    }
};
function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        var info = JSON.parse(body);
        console.log(info);
    }
}
request(options, callback);

Python

import urllib.request
import json

url = "https://brcep-dlfeappmhe.now.sh/78048000/json"
result = urllib.request.urlopen(url)
data = result.read()
encoding = result.info().get_content_charset('utf-8')
print(json.loads(data.decode(encoding)))

Golang

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

type brCep struct {
	Cep         string `json:"cep"`
	Endereco    string `json:"endereco"`
	Bairro      string `json:"bairro"`
	Complemento string `json:"complemento"`
	Cidade      string `json:"cidade"`
	Uf          string `json:"uf"`
	Latitude    string `json:"latitude"`
	Longitude   string `json:"longitude"`
	Ddd         string `json:"ddd"`
	Unidade     string `json:"unidade"`
	Ibge        string `json:"ibge"`
}

func main() {
    cep := "78048000"
    cepSeguro := url.QueryEscape(cep)

    url := fmt.Sprintf("https://brcep-dlfeappmhe.now.sh/%s/json", cepSeguro)

    req, err := http.NewRequest("GET", url, nil)

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal("Do: ", err)
        return
    }

    defer resp.Body.Close()
    var resultado brCep

    if err := json.NewDecoder(resp.Body).Decode(&resultado); err != nil {
        log.Println(err)
    }

    fmt.Printf("%+v\n", resultado)
}

Ruby

require "net/http"
require "uri"
require 'json'

url = "https://brcep-dlfeappmhe.now.sh/78048000/json"
uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if url =~ /^https/

request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')
response = http.request(request)
if response.code == "200"
    result = JSON.parse(response.body)
    puts(result)
end

PHP

<?php
    header ( "Content-Type: application/json;charset=utf-8" );
    $url = 'https://brcep-dlfeappmhe.now.sh/78048000/json';
    $json = file_get_contents($url);
    echo $json;
?>

Java

C-Sharp

using System;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public string UserAgent = @"Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23 (KHTML, like Gecko) Chrome/11.0.686.3 Safari/534.23";

        public string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            return sr.ReadToEnd();
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox2.Text = HttpGet(textBox2.Text);
        }
    }
}

Delphi

uses idHTTP;

procedure TForm1.ButtonCEPClick(Sender: TObject);
var
    HTTP: TIdHTTP;
    IDSSLHandler : TIdSSLIOHandlerSocketOpenSSL;    
    Response: TStringStream;
    URL: String;
begin
    URL := 'https://brcep-dlfeappmhe.now.sh/78048000/json';
    MemoReturn.Lines.Clear;
    try
        HTTP := TIdHTTP.Create;
        IDSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create;	
        HTTP.IOHandler := IDSSLHandler;	
        Response := TStringStream.Create('');
        HTTP.Get(URL, Response);
        if HTTP.ResponseCode = 200 then
           MemoReturn.Text := Utf8ToAnsi( Response.DataString );
    finally
        Response.Free;
        HTTP.Destroy;
    end;
end;

Rodar localmente

Instalação do Golang

Instalar o Golang https://golang.org/dl.

Instalação dos pacotes

go get -u github.com/gin-gonic/gin
go get -u github.com/subosito/gotenv

Configuração do ambiente

  • A API do CEPAberto necessita do token de autorização e a API do ViaCEP não necessita de token.
  • Renomear o arquivo .env.example para .env e incluir o seu token de acesso da API CEPAberto.com

Executar os testes

$ go test -bench .

brcep

Executar o server

$ go run .\server.go .\cepaberto.go .\viacep.go .\util.go

ou

$ go build && ./brcep.exe

brcep

Acessar a API

Para visualizar os dados acesse http://localhost:3000/78048000/json.

Deploy

Deploy no Heroku

What's Heroku?

$ heroku login
$ git add .
$ git commit -am "deploy"
$ git push heroku master

Deploy no Docker via Zeit Now

What's Now?

$ now login
$ now

Licença de uso

MIT License

Copyright (c) 2017 Leonardo Gregianin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.