Code Monkey home page Code Monkey logo

10-advanced-apis's Introduction

Advanced APIs (3:00)

Objectives

After this lesson, students will be able to:

  • Implement a geolocation API to request a location.
  • Process a third-party API response and share location data on your website.
  • Search documentation needed to make and customize third-party API requests.

Preparation

Before this lesson, students should already be able to:

  • Have a solid grasp on HTTP fundamentals.
  • Know how to manipulate the DOM with jQuery.
  • Understand what callback functions are and why they're useful.

Introduction, review, and hook (10 min)

Last class, you registered for a Flickr API key. Tonight you will build an app that will display images posted in the vicinity of a user's current location.



LocalLandscapes: Let's Get to Building! (25 min)

On list of Flickr endpoints:

  • Ask students to pair up (not for programming, just for this exercise)
  • Give class a couple minutes to explore the list, and drill down into at least 2 endpoints
  • Which endpoint will let us find photos based on a user’s location?

  • We can see that as long as we pass certain query values (latitude, longitude, radius and category) we will be given a response containing the landscape photos we want.
  • Awesome! Now that we know our app idea is doable, let's start setting it up.

Get Flickr Credentials

We signed up for an Flickr API in the last class. You should now see the application you created on your Apps By You page:

https://www.flickr.com/services/apps/by/me

Who can remind us why it's not good practice to share API keys?

Starter Code Review (5 min)

Alright, now that all our app configuration is setup, go ahead and open the starter code in your text editor.

  • You have an index.html: HTML file with Bootstrap and jQuery libraries made available via CDNs. The CSS and JS files are connected.
    • The CSS styling gives our app some very basic styling and the app.js file doesn't contain any code...yet.
  • The HTML file references a js/keys.js file. Create that now, and create a variable called apiKey, then copy your API key from the Flickr website as the value and save the file.

app.js
  • Open app.js in your editor
  • We want to wait until the DOM has finished loading before our code is parsed and run.
  • How do we do that with jQuery?
// app.js
$(function() {
  // DOM is now ready

  
});

Get User's Location (20 min)

Remember, our app design is to find posted landscape photos based off our user's location. So what information do we need to get? ( user's location )

Let's go back to the documentation for the endpoint we identified, photos.search. The Location search requires latitude, longitude, and radius. To specify that we want landscapes, we need to use the tags parameter. These are the only requirements we've outlined for the Flickr content we want in our project.


Geolocation

Modern browsers offer a navigator object which we can use to get location data. Google mdn navigator then open the documentation and outline it for students.

Let's go ahead and further our conditional logic to grab the user's location after they open the app. Start with if/else, then fill in getCurrentPosition code.

...


  // check if navigator geolocation is available from the browser
  if (navigator.geolocation) {
    // if it is use the getCurrentPosition method to retrieve the Window's location
    navigator.geolocation.getCurrentPosition(function(position) {
      console.log('lat: ' + position.coords.latitude);
      console.log('lon: ' + position.coords.longitude);

})
  } else {
    $('.images').append('Sorry, the browser does not support geolocation');
  }

...
  • The first thing we do is check to see if the browser has the navigator.geolocation object we need. Then if it does we can go ahead and call on its method getCurrentPosition.
    • getCurrentPostion takes a callback as an argument which will return a position object.
    • position contains a coords object which will have the latitude and longitude values we're looking for.

Reload the page in the browser and notice the Geolocation prompt. If you're having issues:

  • Try a different browser
  • Clear cookies

Then after you allow the app to know your location, check your console for the console.log statements.



Call Flickr Endpoint (10 min)

What does the code we've written so far do? (get user's lat and long)

Now that we have the info we need to ping our Flickr endpoint (lat, long), let's make an API request for local photos!

  • look at the structure of returned data
  • whiteboard the structure
  • navigate through together to find the info we want: photos.photo.length
  • Add the if/else statement
...
      console.log('lat: ' + position.coords.latitude);
      console.log('lon: ' + position.coords.longitude);
  
  // All code from here on down is new code, including the closing });

      // Now that we have the user's location, let's search the API for landscape photos nearby
      let url = 'https://api.flickr.com/services/rest/?'; // base URL
      // Object storing each key and value we need in our query.
      // This makes it clear what options we're choosing, and makes it easier
      // to change the values or add/remove options.
      let searchOptions = {
        method: 'flickr.photos.search', // endpoint
        api_key: apiKey, // stored in js/keys.js
        tags: 'landscape',
        media: 'photos',
        lat: position.coords.latitude,
        lon: position.coords.longitude,
        radius: 10,
        radius_units: 'mi',
        format: 'json',
        nojsoncallback: 1,
        extras: 'url_n',
        content_type: 1,
        safe_search: 1,
        sort: 'relevance',
      };
      // loop through the searchOptions object and append each key and value
      // to the url variable to build the full search URL
      for (let key in searchOptions) {
        url += '&' + key + '=' + searchOptions[key];
      }
      console.log(url);

      // Now that we've built our URL, we can send our GET request
      $.get(url).done(function(response) {
        console.log(response);
        if (response.stat === 'fail') {
          console.log(response.message); // point out that for end users, we'll want to use DOM manipulation, but this is a quick and dirty
      // way of seeing if there's an error while we're building the app
        } else if (response.photos.photo.length === 0) {
          console.log('No photos found!'); // same as previous
        } else {
          // Handle the successful response here
          console.log('Request succeeded!');// note that we will replace this with code to handle the data when it's received; this is just
          // to make sure our code is working to this point
        }
      });

...

Handle Response: Independent Practice (15 min)

  • Now that we can successfully call upon the Flickr API for resources, it is up to you to define the handleResponseSuccess callback function.
  • What's the data type of the data being returned? Check the Example Response section
  • What's the structure of the data being returned?
  • Your function should iterate through your response data, creating an image element each time with the given image url from the API.
  • Add a class image to the image and append it to .images which already exists in the HTML.
  • Once again, use as much jQuery as possible.
  • Check out jquery.each(), which is similar to but different from the .each() method we used earlier.

hint: The data you're looking for is somewhere in response.photos.

Ask for a volunteer to summarize the instructions.

Handle Response Review

function handleResponseSuccess(response) {
  let allData = response.photos.photo; // not a jQuery object, so we have to use $.each below
  $.each(allData, function() {
    let element = $('<img>').attr('src', this.url_n).addClass('image');
    $('.images').append(element);
  });
}
  • results may include paintings and other lower quality or repetitive images
  • walk through examining data and noticing lack of title attributes for these
  • add if clause
  • now check results

Your code should look something like the following:

function handleResponseSuccess(response) {
  let allData = response.photos.photo; // not a jQuery object, so we have to use $.each below
  $.each(allData, function() {
    // photos without titles may not be carefully tagged, so exclude them 
    if (this.title !== '') {
      let element = $('<img>').attr('src', this.url_n).addClass('image');
      $('.images').append(element);
    }
  });
}

And your app should be rendering the response images!


API Exploration: Independent Practice (20 min)

  • Let's get some more practice with reading API documentation and customizing our search results.
  • Take a look at the search documentation and modify our API request to also:
    • Return 30 photos instead of the default 100
    • Sort results by relevance

Bonus

Bonus 1: Return URLs for larger images (Hint: Check out the extras argument at https://www.flickr.com/services/api/flickr.photos.search.html  and look at the Size Suffixes section at https://www.flickr.com/services/api/misc.urls.html).

Bonus 2: Instead of landscapes, return photos from a different category (see popular tags at https://www.flickr.com/photos/tags/)

Bonus 3 (challenging): Implement OAuth and display the current user’s information on the site after a successful login. See authentication documentation at https://www.flickr.com/services/api/auth.oauth.html and the jso library at https://github.com/andreassolberg/jso.


Final questions & exit tickets (10 min)

10-advanced-apis's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.