Using fetch, async, and await, you’ll request information from the Foursquare API and OpenWeather API to create a travel website.
Before you begin, you’ll need to register for developer accounts for both of the APIs above. They’re both free.
For Foursquare, once you make an account, create a new app and fill out the form (you can put any link in the “App or Company URL” field). The Foursquare API will then give you a client ID and a client secret. You’ll need to save both of those in main.js.
For OpenWeather, follow the instructions for the I. Registration process: How to start. When prompted, use your first name, and other for the OpenWeather questions for their data collection. OpenWeather will give you an API Key, which you’ll also need to save in main.js.
You can view a live version of this project here.
-
Save the client ID you obtained from the Foursquare API to const
clientId. -
Save the client secret you obtained from the Foursquare API to const
clientSecret. -
Create a const called
url. Check the Foursquare documentation to see the explore venue API endpoint.
Add the near parameter without a value. To add a query to the end of a URL, be sure to use ? followed by the first key (near) and an =. You’ll add the value of the near parameter to this URL string when you make the request itself.
-
Save the API Key you obtained from OpenWeather to const
openWeatherKey. -
Create a const called
weatherUrl, save'https://api.openweathermap.org/data/2.5/weather'as the value.
See examples of OpenWeather API calls under ‘Examples of API calls’ on the OpenWeather documentation.
- The following steps will guide you through constructing the
getVenues()function which is called fromexecuteSearch().
Turn getVenues() into an asynchronous function that returns a Promise.
-
Inside of that function, add a const called
city. Save the value from the user’s input field on the page with$input.val(). -
Add a const called
urlToFetch. This string will contain the combined text of the entire request URL
- the API endpoint URL
- the user’s input city
- a
limitparameter with the number of venues you wish to return (use 10) - the
client_idparameter and your client ID - the
client_secretparameter and your client secret - the
v(version) parameter and today’s date in this format:YYYYMMDD - Each key-value parameter pair should be joined to the others with
&. For instance, to request 5 venues with a client ID of 1234, that portion of the URL would belimit=5&client_id=1234.
-
Add
try/catchstatements with empty code blocks. -
In the catch code block, log the error to the console.
-
In the try code block, use
fetch()to send a GET request tourlToFetch. await the response and save it to a variable calledresponseusing the const keyword. -
Create a conditional statement that checks if the
okproperty of the response object evaluates to a truthy value. -
Log the response to the console. In the browser window with the Wanderlust page, enter a city in the search field and submit. Make sure that you have your own browser’s JavaScript console open so that you can see the response that is logged to the console.
-
Notice that the response includes the URL you requested but doesn’t include the information you asked for. Copy and paste the URL into a new tab in your browser. It might be difficult to read, so try using an extension such as JSON View Pro to parse the data. If you don’t want to use an extension, you can also try JSON Formatter. Examine the object.
-
Convert the response object to a JSON object. await the resolution of this method and save it to a variable called
jsonResponseusing the const keyword.
- Explore the object in the console. There’s a lot of information in there. Let’s save some of that data to a variable called
venues. Specifically, follow this nesting chain from the jsonResponse variable to get an array of venue data:
- the response property (an object)
- the groups property (an array)
- the first element of groups
- the items property (an array of venue data)
- the first element of groups
- the groups property (an array)
- Log
venuesto the console and see what the API sent back. There should be an array with the number of objects you selected in the limit parameter. You’ll only want the venue property inside of these objects. Use.map()to save these venues to the venues array from the previous step.
Add .map(parameter => parameter.valueToStore) to the end of the code from the previous step.
-
Return
venuesas the very last line of the try code block. -
Run the code and see what is logged to the console now!
- The following steps will guide you through constructing the
getForecast()function which is called fromexecuteSearch().
Turn getForecast() into an asynchronous function that returns a Promise. Add empty try/catch blocks inside. Log the error inside the catch block.
- Before the try code block, create a const called
urlToFetchthat includes:
- the base
weatherUrl - the q parameter (representing the location query) with a value of the user’s input (
$input.val()) and your API key as theAPPIDparameter Don’t forget to join parameter key-value pairs after the API key with&.
-
Inside of the try block, await the response of calling
fetch()and passing it the URL you created in a previous step. Save the response to a variable calledresponseusing the const keyword. -
Create a conditional statement that checks the
okproperty of the response object. If this evaluates to a truthy value, await the response of calling.json()on the response object. Save the resolution of this Promise to a variable calledjsonResponseusing the const keyword. -
Log
jsonResponseto the console. Enter a city in the browser and see what is logged! Explore the object! -
Return
jsonResponseat the bottom of the try code block.
-
You will follow the steps and render the data with guidance in the
main.js. -
In
main.js. There’s a function calledrenderVenuesthat calls the.forEach()method on the$venueDivsarray. This is an array of the<div>s inindex.htmlwhere you will render the information returned in the response from the Foursquare API.
Towards the bottom of this method, there is a variable called venueContent. It’s an empty string for now, but you’ll be replacing it with an HTML string to render correct venue information.
Start by creating a const venue to represent the individual venue object inside of the .forEach() callback. Save the current venue at venues[index] to this variable.
-
Create a
venueIconconst to save the value of the object representing the venue icon. This is accessible as the icon property of the first element in the array ofcategoriesof thevenueobject. -
Now, construct the full source URL for the venue icon. The
venueIconhas a prefix and suffix field used to construct a source path. You can inspect more information about the icon object in the Response Fields and sample Response in the Foursquare documentation or logvenueIconto the console to inspect it.
Concatenate or combine the prefix property of venueIcon, the string 'bg_64', and the suffix, and save to a const venueImgSrc. 'bg_64' is required to fetch icons with a gray background that will show up against the background of the Wanderlust page.
-
Now construct the HTML string to add the new venue. You can use your knowledge of the venue object shape and this HTML template or follow the steps below.
-
A helper function named
createVenueHTML()has been provided to construct the HTML string to display the venue information. You can examine it inpublic/helpers.js, and it is linked inindex.htmlso that you can use it inmain.js.
Pass createVenueHTML() the venue’s name, location, and image source URL and save the returned string to the venueContent variable.
- Now it’s time to hook up your
renderVenues()function to the data fetched bygetVenues().
In the executeSearch() function towards the bottom of main.js, getVenues() and getForecast() are already being called.
Chain a .then() method to getVenues(). .then()‘s callback function should take a single parameter, venues, and return renderVenues(venues).
Save your code, search for a location, and you should be able to see venue information displayed towards the bottom of the Wanderlust page!
-
You will follow the steps and render the data with guidance in the
main.js. -
Now construct the HTML string to add the weather forecast in the
renderForecastfunction. When it’s called, thejsonResponsereturned from callinggetForecast()will be passed in as day. You can inspect the day object’s shape and this HTML template or follow the steps below. -
A helper function named
createWeatherHTML()has been provided to construct the HTML string to display the weather information. You can examine it inpublic/helpers.js, and it is linked inindex.htmlso that you can use it inmain.js.
Pass createWeatherHTML() the day and save the returned string to the weatherContent variable.
- Time to hook up the forecast data and the render function.
Inside executeSearch(), add a .then() method to getForecast(). .then()‘s callback function should take a single parameter, forecast, and return renderForecast(forecast).
- Congratulations! You should now be able to search for venue and weather details by city and see the response on the page!
Note: The OpenWeather API endpoint we use can take input of the form: city, state, like Baltimore, Maryland. You can read more about the OpenWeather API here.
-
Try out any of the challenges below to get more practice!
-
Fetch more than 4 venues and randomize which ones are added to the page.
-
Include additional information about the weather.
-
Include additional information about each venue from the response.
For a real challenge, try fetching venue photos! This will require an additional request for venue details for each venue, as the photo information is not returned in the initial request.