PageRenderTime 29ms CodeModel.GetById 21ms app.highlight 7ms 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
10* APIs
11
12If you are an academic, it is easy to put yourself live in a world all
13data comes as nice clean =.csv= files, generated from curated,
14expensive databases.
15
16My strong piece of advice is *learn to use APIs!* That is where the
17fun data live, and this is how you can connect data and ideas from
18everywhere and do new things with them.
19
20* Example using Python
21
22As a quick example, I present an some extremely simple code to call
23Duck Duck Go's API.
24
25#+begin_src sh python
26
27import requests
28import json
29from IPython.display import Image
30
31payload =  {"q" : "BBQ",
32           "format" : "json",
33           "pretty" : 1}
34
35r = requests.get('http://api.duckduckgo.com/', params = payload)
36r.url
37rj = r.json()
38Image(url=rj['Image'])
39
40#+end_src
41
42
43You can also view the code in [[http://nbviewer.ipython.org/gist/stephenjbarr/234b609ca63575c55196][this iPython notebook]].
44
45The code has the following structure:
46
471. Lines 1-3 load modules useful for making the request, and displaying the image.
482. =payload= is a JSON structure encapsulating the what we want to ask.
493. The =requests.get= command reaches out to Duck Duck Go's API endpoint, hands it the payload, and gets the response.
504. =r.url= shows how the payload was encoded.
515. =r.json()= takes the answer and transformsit into a JSON structure.
526. The =Image= command displays within an iPython notebook an image given a URL.
53
54I highly suggest going to the notebook and try modifying the =q= object of the payload.
55In fact, download the notebook, [[http://ipython.org/install.html][install iPython]], and play with it yourself.
56
57* Reflect
58  
59  In a few simple lines of code, we have transformed a text string into an image.
60  In Haskell / ML notation, we have a function of type:
61
62  #+begin_src haskell
63get_image :: String -> Picture
64  #+end_src
65  
66  This was done with almost no work on our part!
67  
68  
69