Getting started overview
ViaCep provides a free API for looking up Brazilian postal codes (CEPs) and retrieving corresponding address information. Unlike many API services, ViaCep does not require account creation or API keys, simplifying the initial setup process significantly. Developers can directly make requests to the API endpoint to retrieve address data in various formats, including JSON, XML, and plain text.
The primary function of the ViaCep API is to convert a given CEP into a complete address, including street name, neighborhood, city, and state. This functionality is particularly useful for applications requiring address validation, auto-completion of forms, or logistics planning within Brazil. The API is designed to be RESTful, utilizing standard HTTP GET requests for data retrieval.
The following table provides a quick reference for the steps involved in getting started with ViaCep:
| Step | What to do | Where |
|---|---|---|
| 1. Review Documentation | Understand API structure and request formats. | ViaCep API documentation |
| 2. No Account Needed | No registration or login required. | N/A |
| 3. Construct Request | Formulate a GET request with a valid CEP. | Your code editor/terminal |
| 4. Send Request | Execute the HTTP GET request. | Browser, curl, or programming language HTTP client |
| 5. Process Response | Parse the JSON or XML data returned. | Your application logic |
Create an account and get keys
A key differentiator for ViaCep is its operational model: there is no registration process, and no API keys are required to use the service. This means developers can begin making requests immediately after reviewing the API documentation. This approach eliminates common friction points associated with API integration, such as managing credentials, understanding authentication flows like OAuth 2.0 authorization grants, or handling rate limit tiers specific to API keys.
The absence of keys implies that all requests are treated equally, and the service relies on other mechanisms, such as IP-based rate limiting, to manage traffic and ensure fair usage. For developers, this simplifies the integration code, as there is no need to include authentication headers or parameters in their HTTP requests.
To confirm the non-requirement of authentication, developers can refer to the official ViaCep API documentation, which outlines the API endpoints and request parameters without mentioning any authentication steps. This design choice aligns with ViaCep's commitment to providing a free and accessible service for Brazilian CEP lookups.
Your first request
Making your first request to the ViaCep API involves constructing a simple HTTP GET request to a specific endpoint, replacing a placeholder with the desired CEP. The API supports various response formats, with JSON being the most commonly used for programmatic access.
API Endpoint Structure
The base URL for the API is https://viacep.com.br/ws/. To perform a lookup, append the CEP followed by the desired format. For example, to retrieve data for CEP 01001000 in JSON format, the URL would be:
https://viacep.com.br/ws/01001000/json/
Other supported formats include XML (/xml/), plain text (/txt/), and SOAP (/soap/).
Example Request (cURL)
Using curl, a common command-line tool for making HTTP requests, you can easily test the API:
curl "https://viacep.com.br/ws/01001000/json/"
This command will return a JSON object containing the address details for the specified CEP.
Example Request (JavaScript - Node.js with node-fetch)
For JavaScript environments, particularly Node.js, you can use a library like node-fetch (or the built-in fetch API in modern browsers) to make the request:
async function getAddressByCep(cep) {
try {
const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error("Error fetching address:", error);
}
}
getAddressByCep("01001000");
Example Request (Python)
In Python, the requests library is a common choice for making HTTP requests:
import requests
def get_address_by_cep(cep):
url = f"https://viacep.com.br/ws/{cep}/json/"
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print(data)
return data
except requests.exceptions.RequestException as e:
print(f"Error fetching address: {e}")
get_address_by_cep("01001000")
Expected Response Structure (JSON)
A successful request for CEP 01001000 will return a JSON object similar to this:
{
"cep": "01001-000",
"logradouro": "Praça da Sé",
"complemento": "lado ímpar",
"bairro": "Sé",
"localidade": "São Paulo",
"uf": "SP",
"ibge": "3550308",
"gia": "1004",
"ddd": "11",
"siafi": "7107"
}
This structure provides comprehensive address details that can be directly integrated into your application.
Common next steps
After successfully making your first request to the ViaCep API, consider these common next steps to integrate the service more robustly into your applications:
-
Error Handling: Implement robust error handling for cases where a CEP is not found (the API returns a JSON object with
"erro": true) or when network issues occur. This ensures your application can gracefully manage unexpected responses or connectivity problems. -
Input Validation: Before sending a request to ViaCep, validate the CEP format on the client-side. Brazilian CEPs typically consist of 8 digits. Regular expressions can be used to ensure the input matches the expected format, reducing unnecessary API calls and improving user experience. The Mozilla Developer Network provides a guide to regular expressions for various programming languages.
-
Rate Limiting Considerations: While ViaCep is free and generally robust, excessive requests from a single IP address in a short period might lead to temporary blocking. If your application anticipates a high volume of requests, consider implementing a caching mechanism for frequently accessed CEPs to reduce redundant API calls. For very high-volume scenarios, distribute requests or explore alternatives if issues arise.
-
UI Integration: Integrate the API response into user interfaces for features like address auto-completion in forms. When a user enters a CEP, populate the street, neighborhood, city, and state fields automatically, reducing user input and potential errors.
-
Asynchronous Processing: For web applications, ensure API calls are made asynchronously to prevent blocking the main thread and maintain a responsive user interface. This is crucial for a smooth user experience, especially on slower network connections.
-
SDKs and Libraries: Explore community-contributed SDKs or wrappers for ViaCep in your preferred programming language. While the API is simple enough for direct HTTP calls, an SDK might offer convenience functions and better integration with language-specific patterns. ViaCep lists several community SDKs in its official documentation.
-
Data Storage: For applications that frequently need the same address data, consider storing the retrieved information in a local database or cache. This can improve performance and reduce reliance on external API calls, especially for static address components.
Troubleshooting the first call
When making your first call to the ViaCep API, you might encounter a few common issues. Here’s how to troubleshoot them:
-
Invalid CEP Format:
- Symptom: The API returns an empty response, an error indicating an invalid format, or a specific
"erro": truefield in the JSON response. - Solution: Ensure the CEP is an 8-digit number, without hyphens or other special characters in the URL path (e.g.,
01001000, not01001-000). While the API can sometimes handle hyphens, it's best practice to send a clean 8-digit string.
- Symptom: The API returns an empty response, an error indicating an invalid format, or a specific
-
CEP Not Found:
- Symptom: The API returns a JSON object with
"erro": true. - Solution: This indicates that the provided CEP does not exist in the ViaCep database. Double-check the CEP for typos. This can also occur if the CEP is valid but not yet registered or is a temporary CEP.
- Symptom: The API returns a JSON object with
-
Network Connectivity Issues:
- Symptom: Your HTTP client reports a connection error, timeout, or an inability to resolve the hostname.
- Solution: Verify your internet connection. Check if the ViaCep server is reachable (e.g., by visiting ViaCep's homepage in a browser). Ensure no firewalls or proxies are blocking outgoing HTTP requests from your environment.
-
Incorrect URL or Endpoint:
- Symptom: HTTP 404 Not Found error or an unexpected response structure.
- Solution: Confirm that the URL is exactly
https://viacep.com.br/ws/{CEP}/json/, replacing{CEP}with your 8-digit postal code. Any deviation in the path, such as extra slashes or incorrect format specifiers, can lead to errors.
-
Rate Limiting:
- Symptom: Requests start failing after a period of successful calls, potentially with an HTTP 429 Too Many Requests status code (though ViaCep does not explicitly document this, it's a common practice for free APIs).
- Solution: If you are making a very large number of requests in a short time, the service might temporarily block your IP. Implement a delay between requests or consider caching results for frequently accessed CEPs.
-
CORS Issues (Browser-based applications):
- Symptom: Browser console shows a CORS error (e.g., "Access to fetch at '...' from origin '...' has been blocked by CORS policy").
- Solution: If you are making requests directly from a web browser (client-side JavaScript), you might encounter Cross-Origin Resource Sharing (CORS) restrictions. ViaCep generally supports CORS for common origins, but if you face issues, consider proxying your requests through your own backend server to bypass browser CORS policies.