APIs with Ruby/Rails

Objectives

  • Review the purposes of APIs and why we call them on a server
  • Use httparty to interact with an API
  • Use foreman to load API keys from a .env file

What is an API?

API stands for Application Programming Interface, and they provide a set of tools and methods for interacting with software. When we use an API, we generally interact with software by sending inputs. Once inputs are received, they're processed by the software, and we get output, or a response, from the software.

API Graphic
Figure: API Graphic

Public APIS

We used public APIs during the JavaScript unit. Public APIs can be accessed openly without any authentication.

APIs with Keys

Most robust APIs aren't completely open, in order to protect against abuse and/or malicious requests. Generally, an API will require keys to idenitfy who is connecting to the service. Google, Flickr, and Yelp are some companies that provide open APIs using keys.

When we use Flickr, we'll be given an API key and a secret key. Why two keys? Because math! Science! Security purposes! Here's some interesting explanations on why and how these keys are encrypted/decrypted:

Public APIs in Rails

Many web APIs work similarly to a Rails app. They support CRUD actions via a RESTful interface. Meaning, requests can be made over HTTP to get, post, update, and/or delete data.

Clients for sending requests

  • httparty
    • great for simple requests
  • typhoeus
    • great for sending multiple requests in parallel

Implementing a Public API with iTunes

Objective: Display results from iTunes given a query.

Example call: https://itunes.apple.com/search?term=arcade%20fire

  • create a new rails project
    • setup database
  • create a new controller with index and show methods
  • setup routes
  • add the 'httparty' gem.
  • on index, create a form for submitting a query
  • on show, make a request to the API and show results

Of course, test along the way. Otherwise, you're living in the...

Archer Danger Zone
Figure: Archer Danger Zone

APIs w/keys in Rails

See Environment Variables with Foreman

results matching ""

    No results matching ""