PageRenderTime 947ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/posts/2015-06-26-learn-to-use-apis.org

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