Getting started overview
To begin working with the INEI (Instituto Nacional de Estadística e Informática) API, users need to follow a structured process that includes account creation, credential acquisition, and the execution of a foundational API request. The INEI provides access to a wide array of Peruvian statistical data, which is crucial for academic research, public policy analysis, and market insights within Peru. The API is designed as a RESTful interface, making data accessible programmatically via standard HTTP methods. While the primary documentation is in Spanish, the underlying principles of API interaction remain consistent with general web API best practices.
This guide outlines the essential steps to get started, from registering on the INEI portal to making your first successful data call. Understanding these initial steps is critical for efficiently integrating INEI data into your applications or research workflows.
Quick Reference Table
| Step | What to Do | Where to Find |
|---|---|---|
| 1. Account Creation | Register for a user account on the INEI website. | INEI Homepage > 'Servicios' > 'API de Datos' |
| 2. API Key Generation | Locate and generate your unique API key within your account dashboard. | Your INEI User Dashboard (post-login) |
| 3. Review API Documentation | Familiarize yourself with available endpoints, parameters, and data formats. | INEI API Documentation |
| 4. Construct First Request | Formulate a basic API call using your key and a simple endpoint. | INEI API Documentation examples |
| 5. Execute Request | Use a tool like curl or a programming language's HTTP client to send the request. |
Local development environment (terminal, IDE) |
| 6. Parse Response | Process the JSON data returned by the API. | Local development environment (programming language of choice) |
Create an account and get keys
Accessing the INEI API requires a registered user account and an associated API key. These credentials authenticate your requests and ensure proper usage of the data services.
Account Registration
- Navigate to the INEI Website: Begin by visiting the official INEI homepage.
- Locate API Services: Look for a section related to 'Servicios' (Services) or 'API de Datos' (Data API). This is typically found in the main navigation or footer.
- Initiate Registration: Within the API section, there should be an option to 'Registrarse' (Register) or 'Crear Cuenta' (Create Account). Click on this to begin the registration process.
- Complete Registration Form: You will be prompted to provide personal information such as your name, email address, and desired password. Ensure all required fields are filled accurately. Some fields might require Peruvian identification details, depending on the specific registration flow.
- Verify Email: After submitting the form, INEI typically sends a verification email to the address you provided. Follow the instructions in this email to activate your account. This often involves clicking a confirmation link.
API Key Generation
- Log In: Once your account is active, log in to the INEI portal using your newly created credentials.
- Access Dashboard/Profile: After logging in, navigate to your user dashboard or profile settings. Look for a section explicitly labeled 'API Keys', 'Credenciales API', or 'Mis Aplicaciones'.
- Generate New Key: Within this section, there should be an option to generate a new API key or token. This process usually involves a single click. The generated key is a unique string of characters that acts as your authentication credential.
- Securely Store Your Key: Your API key is sensitive. Treat it like a password. Do not embed it directly in client-side code, commit it to public version control systems, or share it unnecessarily. Best practices for API key management suggest using environment variables or secure configuration files to protect your API keys.
Your first request
With an active account and a generated API key, you are ready to make your first call to the INEI API. This example will use a common command-line tool, curl, for simplicity, but the principles apply to any programming language with HTTP client capabilities.
Understanding the API Structure
The INEI API is RESTful, meaning it uses standard HTTP methods (GET, POST, etc.) and typically returns data in JSON format. Endpoints are structured hierarchically, often reflecting the statistical categories available. For instance, an endpoint might look like /v1/data/census/population. Refer to the official INEI API documentation for specific endpoint details, available parameters, and expected response formats.
Example Request with curl
Let's assume a hypothetical INEI endpoint for retrieving basic population data. (Note: Always consult the official INEI API documentation for the exact, current endpoints and parameters, as these are subject to change.)
curl -X GET \
"https://api.inei.gob.pe/v1/data/population/total?year=2020®ion=Lima" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Accept: application/json"
Explanation of components:
curl -X GET: Specifies that this is an HTTP GET request, used for retrieving data."https://api.inei.gob.pe/v1/data/population/total?year=2020®ion=Lima": This is the target URL (endpoint).https://api.inei.gob.pe: The base URL for the INEI API./v1/data/population/total: A hypothetical path to a specific resource (e.g., total population data).?year=2020®ion=Lima: Query parameters that filter or specify the data requested. Here, we're asking for data for the year 2020 and the Lima region.-H "Authorization: Bearer YOUR_API_KEY": This is the authentication header. ReplaceYOUR_API_KEYwith the actual API key you generated. TheBearertoken scheme is a common method for authenticating API requests in OAuth 2.0 contexts.-H "Accept: application/json": This header tells the API that you prefer the response to be in JSON format.
Expected Response
A successful request will typically return a JSON object containing the requested data. For example:
{
"data": [
{
"year": 2020,
"region": "Lima",
"total_population": 10807800,
"unit": "people"
}
],
"metadata": {
"source": "INEI",
"last_updated": "2023-01-15"
}
}
This JSON structure includes the actual data array and often a metadata object providing context about the data's origin and freshness.
Common next steps
After successfully making your first API call, consider these next steps to deepen your integration and leverage the full potential of the INEI API:
- Explore More Endpoints: Review the comprehensive INEI API documentation to discover other available datasets and endpoints. INEI offers a wide range of statistics, including economic indicators, social statistics, and demographic projections.
- Parameterization and Filtering: Experiment with different query parameters to filter, sort, and paginate data. Understanding how to precisely request the data you need will reduce bandwidth and processing overhead.
- Error Handling: Implement robust error handling in your application. The API will return specific HTTP status codes (e.g., 400 for bad request, 401 for unauthorized, 404 for not found, 500 for server errors) and often include error messages in the JSON response body. Proper error handling ensures your application gracefully manages unexpected responses.
- Data Storage and Processing: Decide how you will store and process the retrieved data. For large datasets, consider using a database or data lake solution. For analysis, tools like Python with libraries such as Pandas or R are commonly used.
- Rate Limiting: Be aware of any rate limits imposed by the INEI API. Exceeding these limits can lead to temporary blocks. The documentation typically specifies these limits and provides guidance on how to manage them, for example, by introducing delays between requests.
- Stay Updated: The INEI regularly updates its data and may occasionally revise API endpoints or introduce new versions. Subscribe to any INEI developer newsletters or announcements to stay informed about changes.
Troubleshooting the first call
Encountering issues during your first API call is common. Here's a guide to diagnose and resolve frequent problems:
Common Error Codes and Solutions
- HTTP 401 Unauthorized:
- Issue: Your API key is missing, incorrect, or expired.
- Solution: Double-check that you've included the
Authorization: Bearer YOUR_API_KEYheader. Ensure the key is copied correctly from your INEI dashboard and has not expired. Generate a new key if necessary.
- HTTP 403 Forbidden:
- Issue: Your API key might not have the necessary permissions for the requested resource, or your IP address might be blocked.
- Solution: Verify your account's permissions in the INEI portal. If you suspect an IP block, contact INEI support.
- HTTP 404 Not Found:
- Issue: The endpoint URL is incorrect or the requested resource does not exist.
- Solution: Carefully compare your request URL with the official INEI API documentation. Pay attention to casing, spelling, and path segments.
- HTTP 400 Bad Request:
- Issue: The request parameters are invalid, missing, or malformed.
- Solution: Review the documentation for the specific endpoint you are calling. Ensure all required parameters are present and correctly formatted (e.g., correct data types, valid ranges).
- HTTP 429 Too Many Requests:
- Issue: You have exceeded the API's rate limits.
- Solution: Implement a delay between your requests or use a backoff strategy. Check the INEI documentation for specific rate limit details.
- HTTP 5xx Server Error:
- Issue: An error occurred on the INEI server side.
- Solution: This is generally not an issue with your request. Wait a few minutes and try again. If the problem persists, check the INEI status page or contact their support.
General Troubleshooting Tips
- Verify Internet Connection: Ensure your machine has an active and stable internet connection.
- Check for Typos: Even small typos in URLs, headers, or API keys can cause requests to fail.
- Use a REST Client: Tools like Postman or Insomnia can help you construct and test API requests more easily, providing clear feedback on responses and headers.
- Consult Documentation: The INEI API documentation is your primary resource for understanding valid endpoints, parameters, and expected behaviors.
- Seek Community Support: If INEI provides a developer forum or community, search for similar issues or post your question there.