In-class Excercises: APIs
Part 1: CartoDB's SQL API
- Continue using the CartoDB table and SQL queries from last class if you have them available.
- Create a URL in your text editor that uses CartoDB's SQL API to fetch data. It should be of this form:
Wherehttps://{account}.cartodb.com/api/v2/sql?q={sql}
{account}
is replaced with your CartoDB username and{sql}
is replaced with an SQL query. - Go to this URL using your browser.
- Select the entire response you get back (all the text that shows up in your browser) and copy it.
- Open your JavaScript console, type the following:
Paste the copied text, addresponse = JSON.parse('
')
to close the quotes and function call and hit[enter]
. - Explore the response using the console. Type
response
, hit[enter]
and see the results. - The data is stored in the key
rows
. View the contents of this by enteringresponse.rows
in your console and pressing[enter]
. rows
is an array. In the console, examine the first row.- Can you find the data within the response's rows?
Part 2: Using CartoDB's SQL API in jQuery
Here we do the same as we did in Part 1, but entirely in JavaScript.
- Make an HTML page and load jQuery on it. The
body
can be empty. - Use jQuery's
$.getJSON()
function to fetch the URL you created in Part 1. - Log out some of the rows' contents using
console.log()
.
Part 3: Adding data to a map
- Write an SQL query that selects some of the Airbnb listings from the table you have loaded in CartoDB.
- Test the query in CartoDB to ensure that it works.
- Using this jsbin as a starting point, use the CartoDB SQL API, jQuery, and Leaflet to display the results of your query on a map.
Part 4: Adding data to an element on a page
- Write an SQL query that selects the average, minimum, and maximum price of the Airbnb listings you have loaded in CartoDB.
- Test the SQL query in CartoDB to ensure that it works as expected.
- Using this jsbin as an example, put each of the values returned by the SQL API in their own
span
elements on your page.