Authentication overview
The Mexico API offers various authentication mechanisms to secure access to its geospatial services, including Geocoding, Reverse Geocoding, Mapping, and Places APIs. The choice of authentication method depends on the application's requirements, such as the level of security needed, the type of client application (server-side, client-side, mobile), and whether user consent for data access is necessary. For most direct API calls, particularly from server-side applications, API keys provide a straightforward and effective method for authenticating requests. For applications integrating with user accounts or requiring delegated authorization, OAuth 2.0 is the recommended protocol, offering a more robust and secure framework for managing access tokens and user permissions. All authentication methods are designed to protect both the API and the data being transmitted, ensuring that only authorized requests are processed. Developers are encouraged to review the official Mexico API documentation for specific implementation details and current best practices.
Supported authentication methods
Mexico supports two primary authentication methods for its API:
- API Keys: A simple, token-based authentication method where a unique key is generated and provided by the Mexico developer portal. This key is included with each API request to identify the calling application and authenticate it. API keys are suitable for server-to-server communication or applications where the key can be securely stored and managed. They are generally easier to implement for quick integrations and usage tracking.
- OAuth 2.0: An industry-standard protocol for authorization that enables third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by orchestrating an approval interaction between the resource owner and the HTTP service. OAuth 2.0 is recommended for applications that interact with user data, require fine-grained access control, or operate in environments where API keys might be exposed (e.g., client-side applications). It involves obtaining access tokens, often through a multi-step flow, which are then used to authorize subsequent API requests. The OAuth 2.0 specification outlines various grant types to suit different application scenarios.
The following table summarizes the supported authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Server-side applications, quick integrations, public data access where key exposure risk is low. | Moderate (relies on key secrecy) |
| OAuth 2.0 | Client-side applications, mobile apps, user-facing applications requiring delegated authorization, access to sensitive user data. | High (token-based, temporary, user-consented) |
Getting your credentials
To begin using the Mexico API, you must first obtain the necessary authentication credentials. The process is managed through the Mexico developer portal:
- Sign Up/Log In: Navigate to the Mexico API homepage and either create a new developer account or log in to an existing one.
- Access Developer Dashboard: Upon logging in, you will be directed to your developer dashboard. This is your central hub for managing applications, monitoring usage, and accessing credentials.
- Create a New Application: Most APIs require you to register your application. Look for an option like "Create New Application" or "Manage Apps." Provide a name for your application and, if prompted, specify its type (e.g., web, mobile, server-side).
- Generate API Key: For API Key authentication, once your application is registered, the system will typically generate an API key for you. This key will be displayed on your application's details page. It is crucial to copy this key immediately and store it securely, as it may not be retrievable later.
- Configure OAuth 2.0 Credentials: If you plan to use OAuth 2.0, you will need to configure additional settings within your application's details. This usually involves defining redirect URIs (callback URLs) where users will be sent after authorizing your application. The system will then provide you with a Client ID and a Client Secret. The Client ID is public, but the Client Secret must be kept confidential and never exposed in client-side code. For more information on setting up OAuth 2.0 for web applications, consult the Google OAuth 2.0 web server applications guide, which provides a general framework applicable to many OAuth implementations.
- Review Quotas and Usage: Your developer dashboard will also provide information on your current API usage and any associated quotas, including details on the Mexico API free tier of 5,000 requests per month.
Always refer to the specific credential management section within the Mexico API documentation for the most up-to-date and precise instructions.
Authenticated request example
Here are examples of how to make an authenticated request using both API keys and OAuth 2.0 with the Mexico API. These examples assume you are making a request to the Geocoding API endpoint, which might look like /v1/geocode.
API Key Example (Python)
This Python example demonstrates how to include an API key in a query parameter. While some APIs prefer API keys in headers, Mexico's documentation indicates support for query parameters for simpler use cases.
import requests
API_KEY = "YOUR_MEXICO_API_KEY"
BASE_URL = "https://api.mexico.com/v1/geocode"
ADDRESS = "Paseo de la Reforma 222, Mexico City"
params = {
"address": ADDRESS,
"apiKey": API_KEY # API key included as a query parameter
}
try:
response = requests.get(BASE_URL, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print("Geocoding Result:")
print(data)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
In this example, YOUR_MEXICO_API_KEY should be replaced with the actual API key obtained from your developer dashboard. The key is passed as a query parameter named apiKey.
OAuth 2.0 Example (JavaScript - Client-side, conceptual)
For client-side applications using OAuth 2.0, the process typically involves obtaining an access token first. This conceptual JavaScript example shows how to use an obtained access token in the Authorization header. The actual token acquisition flow (e.g., Implicit Grant or Authorization Code Flow with PKCE) would precede this step.
const ACCESS_TOKEN = "YOUR_OBTAINED_OAUTH_ACCESS_TOKEN";
const BASE_URL = "https://api.mexico.com/v1/geocode";
const ADDRESS = "Av. Insurgentes Sur 1234, Mexico City";
async function getGeocodeWithOAuth() {
try {
const response = await fetch(`${BASE_URL}?address=${encodeURIComponent(ADDRESS)}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`, // Access token in Authorization header
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Geocoding Result:", data);
} catch (error) {
console.error("An error occurred:", error);
}
}
getGeocodeWithOAuth();
Here, YOUR_OBTAINED_OAUTH_ACCESS_TOKEN represents a valid access token. The token is sent in the Authorization header with the Bearer scheme, which is standard for OAuth 2.0. The process of obtaining this access token would involve redirecting the user to Mexico's authorization server, where they grant permission, and then receiving the token back at your configured redirect URI.
Security best practices
Adhering to security best practices is essential when integrating with any API, including Mexico's, to protect your application, user data, and API credentials. Neglecting these practices can lead to unauthorized access, data breaches, and service interruptions.
- Protect your API Keys:
- Never embed API keys directly in client-side code: This includes JavaScript in web pages, mobile application bundles, or any publicly accessible code. Keys embedded this way can be easily extracted by malicious actors.
- Use environment variables: For server-side applications, store API keys in environment variables rather than hardcoding them into your source code. This keeps keys out of version control and allows for easier rotation.
- Server-side proxy: If client-side applications need to access the API, route requests through a secure server-side proxy that adds the API key before forwarding the request to Mexico's API. This keeps the key on your server.
- Restrict API key usage: If available, configure restrictions on your API keys within the Mexico developer portal. For example, restrict an API key to specific IP addresses or HTTP referrers if your application operates from known locations.
- Rotate keys regularly: Periodically generate new API keys and revoke old ones. This minimizes the window of opportunity for a compromised key to be exploited.
- Secure OAuth 2.0 Implementations:
- Keep Client Secrets confidential: Just like API keys, Client Secrets must never be exposed client-side. They are used in server-side exchanges for the Authorization Code Grant type.
- Validate Redirect URIs: Ensure that your registered redirect URIs are specific and secure (using HTTPS). This prevents authorization codes or tokens from being sent to malicious endpoints.
- Use PKCE for public clients: For mobile and single-page applications (public clients), always implement the Proof Key for Code Exchange (PKCE) extension with the Authorization Code Flow. PKCE mitigates the risk of interception of the authorization code. The IETF RFC 7636 details the PKCE specification.
- Securely store access tokens: Access tokens should be stored securely, preferably in memory for short durations, and refreshed when they expire. Avoid storing them in local storage or cookies without proper security measures (e.g., HttpOnly, Secure flags).
- Implement refresh tokens securely: If refresh tokens are used, they should be treated with the same level of confidentiality as API keys. They allow obtaining new access tokens without user re-authentication.
- Use HTTPS/TLS: Always ensure all communication with the Mexico API occurs over HTTPS (TLS). This encrypts data in transit, protecting credentials and sensitive information from eavesdropping. All modern API interactions should default to TLS 1.2 or higher.
- Error Handling and Logging: Implement robust error handling for authentication failures. Log failed authentication attempts (without logging credentials) to detect potential brute-force attacks or unauthorized access attempts.
- Least Privilege Principle: Grant your application only the minimum necessary permissions required to perform its functions. If the Mexico API offers scope-based permissions, utilize them to limit what a compromised credential can access.
By following these best practices, developers can significantly enhance the security posture of their applications integrating with the Mexico API, safeguarding both their systems and their users' data.