/posts/2015-06-26-learn-to-use-apis.org
Org | 69 lines | 47 code | 22 blank | 0 comment | 1 complexity | 29b593dcea96a8d9fa85879f30bae3a7 MD5 | raw file
- #+TITLE: Learn to use APIs
- #+AUTHOR: Stephen
- #+DATE: 2015-06-25
- #+SEQ_TODO: TODO(t) STARTED(s) WAITING(w) DELEGATED(g) APPT(a) | DONE(d) DEFERRED(f) CANCELLED(c)
- #+HTML_DOCTYPE: html5
- #+OPTIONS: toc:nil
- #+FILETAGS: api python ipython
- #+LATEX_CLASS: myfdparticle
- * APIs
- If you are an academic, it is easy to put yourself live in a world all
- data comes as nice clean =.csv= files, generated from curated,
- expensive databases.
- My strong piece of advice is *learn to use APIs!* That is where the
- fun data live, and this is how you can connect data and ideas from
- everywhere and do new things with them.
- * Example using Python
- As a quick example, I present an some extremely simple code to call
- Duck Duck Go's API.
- #+begin_src sh python
- import requests
- import json
- from IPython.display import Image
- payload = {"q" : "BBQ",
- "format" : "json",
- "pretty" : 1}
- r = requests.get('http://api.duckduckgo.com/', params = payload)
- r.url
- rj = r.json()
- Image(url=rj['Image'])
- #+end_src
- You can also view the code in [[http://nbviewer.ipython.org/gist/stephenjbarr/234b609ca63575c55196][this iPython notebook]].
- The code has the following structure:
- 1. Lines 1-3 load modules useful for making the request, and displaying the image.
- 2. =payload= is a JSON structure encapsulating the what we want to ask.
- 3. The =requests.get= command reaches out to Duck Duck Go's API endpoint, hands it the payload, and gets the response.
- 4. =r.url= shows how the payload was encoded.
- 5. =r.json()= takes the answer and transformsit into a JSON structure.
- 6. The =Image= command displays within an iPython notebook an image given a URL.
- I highly suggest going to the notebook and try modifying the =q= object of the payload.
- In fact, download the notebook, [[http://ipython.org/install.html][install iPython]], and play with it yourself.
- * Reflect
-
- In a few simple lines of code, we have transformed a text string into an image.
- In Haskell / ML notation, we have a function of type:
- #+begin_src haskell
- get_image :: String -> Picture
- #+end_src
-
- This was done with almost no work on our part!
-
-
-