This content applies to a previous version of CARTO
In October 2021 we released a new version of our platform. You can find the latest documentation at docs.carto.com
How to Use the CARTO SQL API from a CARTO.js or CARTO-VL Application
Overview
The CARTO Developer Center provides detailed guidance on making calls to the CARTO SQL API. You can utilize several approaches to send HTTP requests from CARTO.js applications, including the JavaScript Fetch API, Axios, or jQuery Ajax.
JavaScript Fetch API
Note that Fetch API support varies across browsers. Here’s an implementation example:
// 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
For browsers lacking Fetch API support, libraries like Axios provide alternatives:
// 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
Public and publicly-linked datasets permit read operations like SELECT without API credentials. However, write operations (INSERT, UPDATE, DELETE, CREATE TABLE) and private datasets require API keys with appropriate SQL permissions. The master API key grants comprehensive account access and should be protected carefully.
