Questions  /  Working with Data  /  Development

How can I use the CARTO SQL API from a CARTO.js or CARTO-VL application?

Learn how to use the CARTO SQL API

Overview

In this section of the CARTO Developer Center you can find detailed information regarding making calls to the CARTO SQL API.

We can use different options to make the HTTP requests from our CARTO.js application to the CARTO account where the data is located like the JavaScript Fetch API or external libraries like Axios or Jquery Ajax.

JavaScript Fetch API

Before starting, it’s important to highlight that the Fetch API doesn’t work in all web browsers. You can check if the Fetch API is supported for your browser here.

Example of CARTO SQL API request using JavaScript Fetch API:

// request to CARTO account using the Fetch API
fetch(`
    https://cartojs-test.carto.com/api/v2/sql?q=SELECT COUNT(*) FROM ne_10m_populated_places_simple`
)
// we transform the response from the Fetch API into a JSON format
.then((resp) => resp.json())

.then((response) => {
    // we get the data from the request response
    console.log(response.rows[0])
})
.catch(function (error) {
    // check if the request is returning an error
    console.log(error)
});

External JavaScript libraries

If your browser is not able to use the Fetch API, another option to try is an external library like Axios.

Example of CARTO SQL API request using Axios:

// load axios library
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
let SQL_CLIENT = axios.create({
    method: 'get',
    url: 'https://cartojs-test.carto.com/api/v2/sql'
});

/* make a request and put callbacks for success and error events */
SQL_CLIENT.request({
        params: {
            q: "SELECT COUNT(*) FROM ne_10m_populated_places_simple"
        },
    })
    .then(function(response){
        // we get the data from the request response
        console.log(response.data.rows[0])
    })
    .catch(function (error) {
        // check if the request is returning an error
        console.log(error)
    });

Authentication

If the dataset is set as Public or Public—with link privacy, we don’t need to add an API KEY to make a read operation like a SELECT. That’s why in the previous requests to the CARTO SQL API we haven’t added the api_key parameter to our requests.

However, if we need to apply a write operation like INSERT, UPDATE, DELETE or CREATE TABLE, or if the dataset is set with Private privacy, we would need to use an API Key to make the SQL API requests.

It is possible to create an API Key with SQL permissions to read or write data in CARTO. In this section of our Developer Center documentation, you can find detailed information about the authentication in CARTO and how to create different API keys for your use case.

The CARTO master API Key gives all kinds of permissions to your account. Anyone with the master API key would be able to remove, create or modify data from your CARTO account without your permission.