Upgrade to Pro — share decks privately, control downloads, hide ads and more …

How to Use an API

Avatar for Emily Chen Emily Chen
February 04, 2015

How to Use an API

Avatar for Emily Chen

Emily Chen

February 04, 2015

Other Decks in Programming

Transcript

  1. • Separate content from presentation: In today's world, where we

    consume content on multiple devices, each device offers a different experience of the same content. • Programmatically access data: Using the API documentation, application developers can derive the URL that they need to request in order to get the data they want.
  2. WHAT KINDS OF DATA CAN YOU GET FROM AN API?

    • Foursquare specials • Meetup checkins • Github commit messages • SoundCloud tracks
  3. A WEB SERVER SITS AROUND AND LISTENS FOR HTTP REQUESTS

    COMING FROM CLIENTS THAT WANT TO ACCESS THE RESOURCES IT MAINTAINS.
  4. • Each resource is addressed at a particular URL. •

    To access a resource, the client sends an HTTP request to the host (server that maintains the resource), specifying the URL of the resource and the operation on that resource. • The “verbs” built into the http protocol (GET, POST, PUT, and DELETE) map directly to application-level operations for retrieving, creating, modifying, and deleting data.
  5. HTTP VERBS THAT ALLOW APPLICATIONS TO READ AND WRITE TO

    WEB SERVICES • GET: read data from server • POST: send new data to the server • PUT, DELETE: modify or delete data
  6. ANATOMY OF A URL: HTTPS://API.GITHUB.COM/SEARCH/REPOSITORIES?Q=TETRIS +LANGUAGE:ASSEMBLY&SORT=STARS&ORDER=DESC • protocol (https): We

    are using the HTTPS protocol, which is a secure version of HTTP • host (api.github.com): A host is usually a domain name, but it could also be an IP Address. • path (/search/repositories): Everything from the first / up to the ? that starts the query string is the path. When making API calls, these paths map to the API method that is being called. • parameters: key-value pairs of the form <key>=<value>, starting with a question mark (?) and separated by an ampersand (&).
  7. GIVEN WHAT WE KNOW ABOUT HTTP REQUESTS, WE EXPECT A

    REQUEST TO POST AN UPDATE VIA THE TWITTER API TO LOOK LIKE THIS
  8. BUT THE SERVICE PROVIDER (IN THIS CASE, TWITTER) NEEDS TO

    KNOW: • Which application is making the request • Which user the request is posting on behalf of • Whether the user has granted the application authorization to post on the user’s behalf
  9. REQUESTS NEEDING AUTHORIZATION CONTAIN AN ADDITIONAL HTTP AUTHORIZATION HEADER TO

    ANSWER THE QUESTIONS THE SERVICE PROVIDER IS CONCERNED ABOUT.
  10. AS AN APPLICATION DEVELOPER, HOW DO YOU GET THE INFORMATION

    YOU NEED TO MAKE AUTHORIZED REQUESTS?
  11. OAUTH • The first widely adopted access control mechanism aimed

    at the needs of APIs and API developers • Now the de facto standard for API authentication • Motivated by a need for users to approve an application to access a service (i.e. Twitter, Instagram, Meetup) on their behalf, without requiring them to share their password
  12. ! 500px Amazon AOL Basecamp Battle.net Bitbucket bitly Box Dailymotion

    deviantART Discogs Dropbox Etsy Evernote Exact Online Facebook Fitbit Flickr Formstack Foursquare GitHub Goodreads Google Google App Engine Groundspeak Huddle Imgur Instagram Intel Cloud Services Jive Software LinkedIn Microsoft (Hotmail, Windows Live, Messenger, Active Directory, Xbox) Mixi MySpace Netflix OpenLink Data Spaces OpenTable PayPal Plurk Reddit salesforce.com Sina Weibo StatusNet Strava Stripe Trello Tumblr Twitter Ubuntu One Viadeo Vimeo VK Withings Xero XING Yahoo! Yammer Yandex Yelp Zendesk
  13. • If you are developing an app FOO that wants

    to use ACoolAPI, you register your app with the ACoolAPI service, which then assigns the FOO client a client_id and client_secret. • FOO can use the client_secret to verify it is sending API requests as FOO, not as SOME_EVIL_APP pretending to be FOO.
  14. AUTHORIZATION FLOW • Which user is the request on behalf

    of? • Has that user granted the application authorization to make this request?
  15. • When FOO client wants to access ACoolAPI on behalf

    of a user, FOO presents its client ID to the service in order to acquire an access token. FOO also specifies an Authorization callback URL that the user should be redirected to after s/he authorizes FOO to access ACoolAPI on his/her behalf. • After the user authorizes FOO to access ACoolAPI on their behalf, they're redirected to a URL that includes an auth code for FOO developers to exchange for an access token. • The app developer POSTs this code, along with some app identification parameters (client_id, client_secret), to the service's access_token endpoint.
  16. EXAMPLE • Client FOO directs user to an authorization prompt

    provided by the service and and provides redirect_uri = http:// myexamplewebapp.com/oauth_page • A successful authentication will redirect the user to http:// myexamplewebapp.com/oauth_page?code=BAR • Developers of the FOO client pass the auth code BAR to request the /oauth/access_token endpoint of ACoolAPI. The service responds with an OAuth access token, which allows FOO to use the service on the user's behalf.
  17. THE APPLICATION DEVELOPER CAN NOW ISSUE REQUESTS TO THE API

    WITH THE NEEDED HTTP AUTHORIZATION HEADER, WITHOUT KNOWING THE USER’S PASSWORD FOR THE SERVICE!
  18. WARNINGS • Don't inadvertently share the client secret of your

    registered app by checking it in on a public Github repo. • If you're building an app that does not have a server component (apps that have the entire source code available to the browser), then you cannot keep the client secret confidential and must use an auth flow that does not require a client secret. OAuth 2.0 specs a different authentication flow for this case.
  19. • Most APIS require authentication over HTTPS to prevent any

    man-in-the-middle sniffing of API credentials. • Support for basic auth is built into every HTTP library.
  20. How is the requested data sent back to the client?

    After an application requests data via a URL, the server sends a response.
  21. JSON • Language agnostic data-interchange format • Stores key-value pairs

    • We will refer to each JSON document as an object.
  22. • The syntax of was inspired by the JavaScript Object

    Literal notation, but there are differences between them. For example, in JSON all keys must be quoted. • Most JSON documents are one big object, but they can also be one big array: [ "This", "Is", { "valid": JSON } ]
  23. JSON DATA TYPES • string: have be delimited by double

    quotes, while in JavaScript, you can use single or double quotes interchangeably • number: in JavaScript you can use Hexadecimal Literals or Octal Literals. In JSON you can use only Decimal Literals. • object: documents can be nested in other documents • array • boolean: true, false • literal: null
  24. Some Python HTTP clients: httplib2, urllib2, requests Libraries contain code

    to build urls, send HTTP requests, and parse responses.
  25. HTTPLIB2 AN OPEN SOURCE THIRD-PARTY HTTP CLIENT LIBRARY THAT SUPPORTS

    FEATURES SUCH AS: • Caching: if it successfully makes a request, httplib2 will store the response temporarily so the next time the same request is made, it can fetch the response without going over the network • Compression: when the HTTP client requests a resource, it can ask the server to send it in compressed format to reduce the amount of data sent over the network. By reducing the size of data sent over the network, more bandwidth is available and transmission times are reduced.