Getting started overview

Getting started with CARTO involves a sequence of steps designed to enable developers to access and utilize its spatial data and analysis capabilities. The process typically begins with account creation, followed by the generation of API credentials. These credentials are then used to authenticate requests to CARTO's APIs, facilitating tasks such as data visualization, spatial analysis, and integration with existing applications. CARTO provides a comprehensive documentation portal to guide users through its platform features and API specifications.

The primary components for initial setup include:

  • Account Registration: Creating a CARTO account to access the platform and its services.
  • API Key Generation: Obtaining the necessary credentials for authenticating API requests.
  • Environment Setup: Configuring a development environment to interact with CARTO APIs, potentially using one of the available SDKs.
  • First API Call: Executing a simple request to confirm connectivity and authentication.

A typical initial workflow can be summarized as follows:

Step What to Do Where to Find It
1. Sign Up Register for a CARTO account. The Starter plan offers usage credits. CARTO Pricing page
2. Get API Key Locate and copy your API key from the CARTO dashboard. CARTO API reference documentation
3. Choose API Select the CARTO API relevant to your task (e.g., SQL API, Data Observatory API). CARTO documentation portal
4. Make Request Construct and send your first authenticated API request. CARTO API reference guides

Create an account and get keys

To begin using CARTO's services, you must first create an account. CARTO offers a Starter plan that includes usage credits, allowing developers to explore the platform without immediate financial commitment. Account registration typically involves providing an email address and setting a password, followed by email verification.

Account Creation Process

  1. Navigate to the CARTO website's pricing page.
  2. Select the 'Starter' plan or another suitable plan if you require more extensive features.
  3. Follow the on-screen prompts to complete the registration form, which usually includes entering your name, email, and creating a password.
  4. Verify your email address by clicking the link sent to your registered email.
  5. Once verified, log in to your new CARTO account.

Obtaining API Keys

After logging in, your API key is essential for authenticating requests to CARTO APIs. This key serves as a unique identifier and authorization token for your account. It is typically found within your CARTO dashboard or user settings area.

  1. From your CARTO dashboard, locate the 'API Keys' or 'Developer Settings' section. The exact path may vary based on UI updates, so refer to the official CARTO documentation for the most current instructions.
  2. Generate a new API key if one is not already provided, or copy an existing one. It is recommended to store your API key securely and avoid hardcoding it directly into client-side applications.
  3. CARTO API keys grant access to your account's resources. Treat them with the same security considerations as other sensitive credentials, such as those for Stripe API keys or PayPal API credentials.

Your first request

With an account created and an API key obtained, you can now make your first authenticated request to a CARTO API. This example will use the CARTO SQL API, a common entry point for querying and managing spatial data within CARTO. The SQL API allows you to execute SQL queries against your datasets and retrieve results in various formats.

Using the CARTO SQL API

The CARTO SQL API endpoint typically follows the pattern: https://{username}.carto.com/api/v2/sql, where {username} is your CARTO account username. You will need to include your API key as a query parameter (api_key) and the SQL query itself (q).

Example: Fetching a Public Dataset

Let's query a public dataset, such as carto_public_data.world_borders, to retrieve a few records. This example assumes you have access to public datasets or have imported your own data into CARTO. For a full list of public datasets and their availability, consult the CARTO documentation.

Python Example (using requests library):

import requests
import json

CARTO_USERNAME = "your_carto_username"  # Replace with your CARTO username
CARTO_API_KEY = "your_api_key"      # Replace with your CARTO API key

SQL_QUERY = "SELECT name, pop_est FROM carto_public_data.world_borders LIMIT 5"

# Construct the API endpoint
API_URL = f"https://{CARTO_USERNAME}.carto.com/api/v2/sql"

params = {
    "q": SQL_QUERY,
    "api_key": CARTO_API_KEY,
    "format": "json"
}

try:
    response = requests.get(API_URL, params=params)
    response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
    
    data = response.json()
    print(json.dumps(data, indent=2))
    
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An unexpected error occurred: {req_err}")
JavaScript Example (using fetch API):

const CARTO_USERNAME = "your_carto_username"; // Replace with your CARTO username
const CARTO_API_KEY = "your_api_key";     // Replace with your CARTO API key

const SQL_QUERY = "SELECT name, pop_est FROM carto_public_data.world_borders LIMIT 5";

const API_URL = `https://${CARTO_USERNAME}.carto.com/api/v2/sql`;

const params = new URLSearchParams({
  q: SQL_QUERY,
  api_key: CARTO_API_KEY,
  format: "json",
});

fetch(`${API_URL}?${params.toString()}`)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(JSON.stringify(data, null, 2));
  })
  .catch(error => {
    console.error("Error fetching data:", error);
  });

Replace "your_carto_username" and "your_api_key" with your actual CARTO credentials. Executing either of these code snippets should return a JSON object containing the requested data, confirming your authentication and connectivity to the CARTO SQL API. For more detailed API specifications, refer to the CARTO Engine API Reference.

Common next steps

After successfully making your first API call, several common next steps can deepen your interaction with the CARTO platform:

  • Explore the CARTO Spatial Data Catalog: CARTO offers a Spatial Data Catalog with access to various public and commercial datasets. Integrating these datasets can enrich your spatial analyses.
  • Data Import and Management: Learn how to upload your own spatial data (e.g., Shapefiles, GeoJSON, CSV) to CARTO. The platform supports various methods for data import and management, allowing you to centralize your geospatial assets.
  • Utilize CARTO Builder: For visual exploration and dashboard creation, CARTO Builder provides a web-based interface. You can visualize your data, apply styling, and create interactive maps without extensive coding. Details are available in the CARTO Builder documentation.
  • Advanced Spatial Analysis with Analytics Toolbox: The CARTO Analytics Toolbox offers a suite of spatial analysis functions. These tools can be accessed via SQL queries or through the Python SDK to perform tasks like clustering, routing, and territory analysis.
  • Integrate with SDKs: For more complex application development, explore the CARTO for React library or the Python SDK (CARTOFrames) to build custom mapping applications and integrate CARTO capabilities into your existing workflows.
  • Webhooks and Real-time Data: Investigate CARTO's support for webhooks to enable real-time data updates or trigger actions based on geospatial events. Understanding how webhooks function can enhance the dynamism of your applications.
  • Security Best Practices: Review CARTO's security documentation to ensure your applications and data interactions adhere to best practices, especially concerning API key management and data access permissions.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps for common problems:

  • Incorrect API Key:
    • Symptom: 401 Unauthorized or 403 Forbidden HTTP status code.
    • Solution: Double-check that your CARTO_API_KEY is correct and has not expired. Ensure there are no leading or trailing spaces. Generate a new key from your CARTO dashboard if necessary, following the CARTO API authentication guide.
  • Incorrect Username or Endpoint:
    • Symptom: 404 Not Found HTTP status code or connection errors.
    • Solution: Verify that your CARTO_USERNAME is accurate and that the API endpoint URL is correctly constructed. The username is typically part of the subdomain (e.g., https://your_username.carto.com/...). Consult the CARTO documentation for the exact API endpoint structure.
  • Invalid SQL Query:
    • Symptom: 400 Bad Request HTTP status code with an error message indicating a SQL syntax error.
    • Solution: Review your SQL_QUERY for syntax errors. Ensure table names and column names are correct and that the query adheres to SQL standards supported by CARTO. Test your query directly in the CARTO Builder's SQL editor to debug. The CARTO SQL API documentation provides query examples.
  • Network or Firewall Issues:
    • Symptom: Connection timeouts or inability to reach the CARTO server.
    • Solution: Check your local network connection. If you are behind a corporate firewall, ensure that access to *.carto.com is permitted. Temporarily disabling a local firewall might help diagnose the issue.
  • Missing or Incorrect Parameters:
    • Symptom: 400 Bad Request with a message about missing mandatory parameters.
    • Solution: Ensure all required parameters (e.g., q for SQL query, api_key) are included in your request and are correctly formatted according to the CARTO API reference.
  • Rate Limiting:
    • Symptom: 429 Too Many Requests HTTP status code.
    • Solution: If you are making numerous requests in a short period, you might hit rate limits. Implement exponential backoff for retries or reduce the frequency of your requests. Information on CARTO's rate limits can be found in the documentation.