Skip to content

Instantly share code, notes, and snippets.

@jsanz
Created December 21, 2017 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanz/838e40ad432f72f121563a6169298eea to your computer and use it in GitHub Desktop.
Save jsanz/838e40ad432f72f121563a6169298eea to your computer and use it in GitHub Desktop.
JS: minimal example of axios and SQL API

As the new carto.js library does not provide a SQL API client, this small example shows how to use a requests library like axios to provide the same functionality with a very similar approach as the old cartodb.SQL client.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>SQL API Example</title>
</head>
<body>
<div>SUM =
<span id="count"></span>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
/* create an axios client to the SQL API */
var API_KEY = 'whatever-with-public/link-datasets',
USER_NAME = 'cartojs-test',
SQL_CLIENT = axios.create({
method: 'get',
url: 'https://' + USER_NAME + '.carto.com/api/v2/sql?',
params: {
api_key: API_KEY
}
});
/* 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) {
if (response && response.data) {
console.log(response.data);
var el = document.getElementById('count');
el.innerHTML = response.data.rows[0]['count'];
} else {
alert('Check the console, something happened');
}
})
.catch(function (error) {
alert('Check the console, something happened');
console.log(error);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment