-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.qmd
992 lines (681 loc) · 26.5 KB
/
index.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
---
format:
revealjs:
theme:
- "theme/my-theme.scss"
chalkboard: true
slide-number: c/t
logo: "https://www.rstudio.com/wp-content/uploads/2018/10/RStudio-Logo-Flat.png"
footer: "[https://kmasiello.github.io/getting-started-apis](https://kmasiello.github.io/getting-started-apis)"
code-copy: true
center-title-slide: false
code-link: true
code-overflow: wrap
highlight-style: a11y
height: 1080
width: 1920
# height: 900
# width: 1440
execute:
eval: true
echo: true
cache: true
---
<h1>Getting Started With APIs</h1>
<h2>[*the ELI5 edition, featuring* `plumber`]{.altred}</h2>
<hr>
<h4>2022-10-21</h4>
<br>
<h3>Katie Masiello, Solutions Engineer at</h3>
![](https://www.rstudio.com/wp-content/uploads/2018/10/RStudio-Logo-Flat.png){.absolute top="425" left="1072" height="95"}
<br>
<h3>`r fontawesome::fa("github", "black")` [github.com/kmasiello/getting-started-apis](https://github.com/kmasiello/getting-started-apis)</h3>
![](images/plumber.png){.absolute top="525" left="1400" width="500"}
::: {.notes}
This talk is personal, it's for me 4 years ago.
- working in propulsion safety and risk analysis group
- download CSV data from ACTS database - fleet info, line number, delivery date, engine type
- grated on me to manually download and read in data. I wanted it all to be programmatic and streamlined, like those commercials
- read about APIs but couldn't figure it out. Google didn't help.
- ran into plumber and got even more confused. I didn't know if I was supposed to use plumber to call the database or which end was up.
- Now it's 4 years later, I'm in a different place in my career working as a solutions engineer at RStudio
- I hope today I can untangle and clarify APIs for anyone who is in this same place that I was
:::
## What is an API?
Wikipedia says:
> An application programming interface (API) is a way for two or more computer programs to communicate with each other.
. . .
<br>
🤔 *I'm not a computer... so what's that got to do with me?*
. . .
Katie says:
. . .
> An API is just a fancy way of accessing a function, from any system, and you don't have to access that function using the same language it was written in.
. . .
Katie's corollary:
> If you can write a function, you can write an API.
::: {.notes}
What you may have heard before, right? It's how machines talk to one another. You're using an API just to call up a website like cnn. 🔽
in my mind you write a function to do something.
an API becomes a way to access that. 🔽
and if you can write a function, you can create an api.
:::
## Systems as Black Boxes
![](images/black_boxes.png){fig-alt="Two black box systems. The left system asks for fleet data, the right system responds with data." fig-align="center"}
. . .
::: columns
::: {.column width="50%"}
### What's inside my system?
. . .
- R?
- Python?
- Excel?
- Tableau?
:::
::: {.column width="50%"}
### What's inside the other system?
. . .
- JavaScript?
- Python?
- R?
- Scratch? ;)
:::
:::
::: {.notes}
Let's talk systems analysis.
We've got two black boxes here, each representing some kind of system. and we need to communicate between them. In the example I mentioned earlier, I was working in R and i wanted data from another system. What I wanted was to request this data programmatically and have it sent to me.
Let's think about what's inside. What do we have here? 🔽
In this illustration, I might be working in Python or R. Maybe it's an excel workbook or tableau dashboard for example.
What do I need to connect with? It could be anything. 🔽
Javascript? R, python? I joek around but it could be something written in BASIC or Scratch. We likely don't even KNOW what the other system is. But does it matter?
🔽
:::
## Systems as Black Boxes
![](images/black_boxes.png){fig-alt="Two black box systems. The left system asks for data, the right system responds with data." fig-align="center"}
::: columns
::: {.column width="50%"}
### What's inside my system?
:::
::: {.column width="50%"}
### What's inside the other system?
:::
:::
<br>
::: {.fragment .fade-up}
::: {style="text-align: center;"}
<h2>🎉 <br>It doesn't matter as long as we agree on a standard way to communicate between systems!</h2>
:::
:::
::: {.notes}
No. 🔽
Here's the important thing. It does not matter what's INSIDE the boxes as long as we can standardize on a means to communicate between the boxes.
:::
## Systems as Black Boxes
![](images/restful.png){fig-alt="Two black box systems. The left system asks for data, the right system responds with data." fig-align="center"}
If the other system's external interfaces are exposed as "API endpoints," and if my system can formulate a REST-based API call, we can communicate.
::: {.notes}
This is the beauty of APIs. Formally we call these REST-based APIs because they follow a defined standard called REST. The way these RESTful APIs communicate is via HTTP which is why people talk about using API calls when you browse the web.
In essence, as long as the system you are using can formulate a REST-based API call, and the receiving end is exposing its interfaces as what are called API endpoints, we can communicate.
:::
## Let's See it in Action 🌧️
How's the weather at Paine Field?
[https://api.open-meteo.com/v1/forecast?latitude=47.9&longitude=-122.3&hourly=temperature_2m, rain,windspeed_10m&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch& timezone=America%2FLos_Angeles](https://api.open-meteo.com/v1/forecast?latitude=47.9&longitude=-122.3&hourly=temperature_2m,rain,windspeed_10m&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch&timezone=America%2FLos_Angeles)
```{r}
library(httr)
httr::GET("https://api.open-meteo.com/v1/forecast?latitude=47.9&longitude=-122.3&hourly=temperature_2m,rain,windspeed_10m&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch&timezone=America%2FLos_Angeles") |>
content(as = "text") |>
jsonlite::fromJSON()
```
::: {.notes}
Let's see an API call. This is a weather API. It's free and publicly available. If I click on it, or drop it in the chat window for you to click on, you'll see the output in the browser.
It's a bit messy but it's readable. Or here is a code snippet for how I'd use this in R. I'll use the `httr` package to formulate the API request and receive a response.
:::
## Think of APIs as a way to access functions
General form of an API:
http://hostname/api_endpoint/?parameter=value
Example function:
```{r}
my_function <- function(argument) {
some_kind_of_operation(argument)
}
```
As an API:
http://hostname/my_function/?argument=value
::: {.notes}
I want to reiterate this concept of APIs as a way to access a function.
In general, api takes this form.
Here's a function.
Here's the function as an analogous API.
:::
## Parts of an API
- **Host:**
- [`http://api.hostname.io/`]{style="background-color:#f7f896"}
- **Endpoint:**
- Resource location (think of this as the function)
- `http://api.hostname.io/`[`endpoint`]{style="background-color:#9ef8f8"}
- **Parameters (optional):**
- Address varying parts of a request (think of these as the arguments)
- `http://api.hostname.io/endpoint/`[`?param1=valueA¶m2=valueB`]{style="background-color:#f9ca9a"}
- **Headers & body (optional):**
- (not in URL) Associated (meta)data
The weather API:
[`https://api.open-meteo.com/`]{style="background-color:#f7f896"}[`v1/forecast`]{style="background-color:#9ef8f8"}[`?latitude=47.9&longitude=-122.3& hourly=temperature_2m,rain,windspeed_10m&temperature_unit=fahrenheit& windspeed_unit=mph&precipitation_unit=inch&timezone=America%2FLos_Angeles`]{style="background-color:#f9ca9a"}
::: {.notes}
Let's talk a little vocabulary.
Host
Endpoint
Parameters
etc.
:::
## API Requests
- Each API endpoint has a different **method**
- GET
- Used to *retrieve* data. Parameters only. No body.
- Everything is in the URL.
- Don't send sensitive data!
- POST
- Used for sending data (files or text).
- Creating or modifying something.
- Other methods:
- PUT
- DELETE (yikes!) ☠️
- HEAD
- and more
::: {.notes}
So we've seen the general form of an API. Let's talk about the types of requests we can make.
Each endpoint has a **method** for how to interact with it. These methods describe the types of action the request does.
As you're getting started, GET and POST will cover you.
:::
## API Reponses
- Default response from an API is JSON object
- Human-readable (to an extent)
- Familiar syntax for working with in R, Python
- Many frameworks support additional response types
- text, csv
- images
- htmlwidgets
- specific file types (e.g., RDS, feather, parquet)
- and more
::: {.notes}
And once we've made our request, an API response can take multiple forms.
The default is JSON.
Most frameworks support additional response types. In Plumber these are called the serializer. It's how the data gets serialized in response.
:::
## Why Should [*You*]{.darkyellow} Build an API?
[What's in your data science toolbox right now?]{.altred}
- Reports
- Presentations
- Spreadsheets
- Interactive Dashboards
[*all these tools are limited to **end user consumption***]{.fragment}
[<br> 😄 "I can enable an analytics pipeline with APIs."]{.fragment}
::: {.notes}
Now we've got a feel for what an API is. When can it be useful?
First I want you to consider what you've got in your toolbox right now.
if we look at the traditional data science toolbox it may include any number of these traditional things.
🔽
but they're all limited to end user consumption.
they require some kind of user interaction.
🔽
an API permits you to eliminate the human interaction.
:::
## Why Should [*You*]{.darkyellow} Build an API?
[Common pain points]{.altred}
* "I've created a Shiny beast!"
* "We are replicating work in every project"
* "How do we share this code with another system / group?"
* "Your model is great, we're going to hand it over to this other team to rebuild it in JavaScript." 😭
::: {.notes}
That's cool. but what about these situations. these are some of the pain points I commonly hear that lead to good discussions around using APIs.
Sometimes you build out a solution but the solution itself becomes the problem in that it's either difficult to maintain or update, or supporting it in production is unwieldy.
or you find you're replicating work like what I was doing with my manual csv download and running it through the same data cleaning script.
Or you need to share your code with another group or system.
Or worse, I die a little inside when I hear this. A team says they have a great model but they handed it over to another team and they are rebuilding it in another language.
:::
## Okay, but how?
::: columns
::: {.column width="50%"}
#### API frameworks
- R --- plumber
- Python --- Flask, FastAPI
- JavaScript --- Node.js, Express.js
:::
::: {.column width="50%"}
#### Deployment options
- RStudio Connect
- Digital Ocean
- Docker
:::
:::
## Our Chosen Tools for Today
::: columns
::: {.column width="50%"}
#### API frameworks
- [R --- plumber]{.darkyellow}
- [Python --- Flask, FastAPI]{style="color:silver;"}
- [JavaScript --- Node.js, Express.js]{style="color:silver;"}
:::
::: {.column width="50%"}
#### Deployment options
- [RStudio Connect]{.darkyellow}
- [Digital Ocean]{style="color:silver;"}
- [Docker]{style="color:silver;"}
:::
:::
## Let's Get to Work! {.center .bigger}
------------------------------------------------------------------------
::: left-column-impact
<h7>[4]{.darkyellow style="font-size: 275px;"} <br>steps to making a plumber API</h7>
:::
::: right-column-impact
<br><img src="images/plumber.png" style="vertical-align:middle" height="350"/><br>
### 1. Make a function
### 2. Add `plumber` decorations
### 3. ⚠️Save as **"`plumber.r`"**
### 4. Publish
:::
## Start Simple: A coin toss example
**Function 1: coin toss**
```{r}
#Function 1: toss once and give me a heads or tails output
coin_toss <- function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
coin_toss()
```
**Function 2: multi toss**
```{r}
#Function 2: toss multiple times and summarize output
multi_toss <- function(n) {
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)) |>
as.data.frame()
}
multi_toss(500)
```
::: {.fragment .fade-up}
::: columns
::: {.column width="40%"}
<br><br>
### Get Ready to Decorate!
:::
::: {.column width="60%"}
![](images/decorate.gif)
:::
:::
:::
::: {.notes}
I'm going to run you through a simple example to get your feet wet. Then we'll look at two additional examples.
we'll begin with a coin toss. we can consider this a really simple model. I have two functions.
🔽
we've done step one. now we get to decorate.
:::
## Sneak Peek: The Finished API
Notice special plumber comments (decorations) with `#*`
```{r}
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: false
#| code-line-numbers: "|1,3,5-6,13-15"
library(plumber)
#* @apiTitle Coin Toss API
#* Toss a coin once and give the result
#* @get /coin_toss
function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
#* Toss a coin multiple times and summarize output
#* @param n the number of times to toss the coin
#* @get /multi_toss
function(n) {
as.data.frame(
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)))
}
```
::: {.notes}
This is the complete API. I want you to see this to see first, it fits on one page. And second, notice how little changed from what I had before. I still have my functions. I just added 🔽 these 7 lines to transform this into an API.
:::
## Make an API --- Add a Title
**Noted with `@apiTitle`**
```{r}
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: false
#| code-line-numbers: "1,3"
library(plumber)
#* @apiTitle Coin Toss API
#* Toss a coin once and give the result
#* @get /coin_toss
function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
#* Toss a coin multiple times and summarize output
#* @param n the number of times to toss the coin
#* @get /multi_toss
function(n) {
as.data.frame(
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)))
}
```
## Make an API --- Add Endpoint Descriptions
**What does each endpoint (think: function) do?**
```{r}
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: false
#| code-line-numbers: "5,13"
library(plumber)
#* @apiTitle Coin Toss API
#* Toss a coin once and give the result
#* @get /coin_toss
function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
#* Toss a coin multiple times and summarize output
#* @param n the number of times to toss the coin
#* @get /multi_toss
function(n) {
as.data.frame(
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)))
}
```
## Make an API --- Add Endpoint Parameters
**Noted with `@param`; these are your function arguments** (optional)
```{r}
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: false
#| code-line-numbers: "14"
library(plumber)
#* @apiTitle Coin Toss API
#* Toss a coin once and give the result
#* @get /coin_toss
function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
#* Toss a coin multiple times and summarize output
#* @param n the number of times to toss the coin
#* @get /multi_toss
function(n) {
as.data.frame(
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)))
}
```
## Make an API --- Specify Endpoint and Method
**Noted with `@get`, `@post`, etc.**
```{r}
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: false
#| code-line-numbers: "6,15"
library(plumber)
#* @apiTitle Coin Toss API
#* Toss a coin once and give the result
#* @get /coin_toss
function() {
sample(c("heads", "tails"), 1,
prob = c(0.5, 0.5), replace = TRUE)
}
#* Toss a coin multiple times and summarize output
#* @param n the number of times to toss the coin
#* @get /multi_toss
function(n) {
as.data.frame(
table(sample(c("heads", "tails"), n,
prob = c(0.5, 0.5), replace = TRUE)))
}
```
::: {.fragment .fade-up}
::: {style="text-align: center;"}
<br><h2>🎉<br>*et voilà!*</h2>
:::
:::
## Short detour: The Swagger Interface
**Plumber (and FastAPI) bake in a Swagger UI for interacting with your API**
::: panel-tabset
### Static image
![](images/swagger.png){fig-align="center" height="800px"}
### Demo
![](images/swagger.gif){fig-align="center" height="800px"}
:::
::: {.notes}
Let's detour. The Swagger interface in the RStudio IDE and on RStudio Connect permits you to interact with the API.
I'll run this locally and show this.
:::
## Publish the API
Deploy to RStudio Connect [using your preferred method](https://solutions.rstudio.com/data-science-admin/deploy/) (push button deployment, git-backed deployment, or programmatic).
::: {style="text-align: center;"}
[**https://colorado.rstudio.com/rsc/coin_api/**](https://colorado.rstudio.com/rsc/coin_api/){.uri}
<a href="https://colorado.rstudio.com/rsc/coin_api/" target="_blank"><img src="images/published.png" alt="Image of API deployed on Connect" style="height:700px;"/></a>
:::
## Are you warmed up? {.center .bigger}
## How might you use an API?
- Standardize your data munging and other business logic
- Pull the heavy lifting out of your Shiny app and into an API
- Query your model from Slack, Tableau, other web apps, ...
## Example: Standardize Data Processing
::: panel-tabset
### Data Formatting
Use case: You have a common source of fleet data and perform the same routine data cleaning and formatting as part of routine analysis.
::: columns
::: {.column width="50%"}
```{r}
#| class-source: longest_code_block
#| classes: longest_code_block
#| echo: true
#| eval: false
library(nycflights13)
library(dplyr)
fleet_lookup <- function(carrier){
carrier_tbl <- flights %>%
select(carrier, tailnum) %>%
distinct()
planes %>%
mutate(manufacturer=recode(manufacturer, "AIRBUS INDUSTRIE"="AIRBUS",
"MCDONNELL DOUGLAS CORPORATION" = "MCDONNELL DOUGLAS",
"MCDONNELL DOUGLAS AIRCRAFT CO" = "MCDONNELL DOUGLAS")) %>%
filter(engine %in% c("Turbo-jet", "Turbo-fan")) %>%
left_join(carrier_tbl) %>%
distinct() %>%
filter( carrier == {{ carrier }}) %>%
group_by(manufacturer, model) %>%
tally() %>%
arrange(desc(n))
}
fleet_lookup("UA")
```
:::
::: {.column width="50%"}
```{r}
#| echo: false
#| eval: true
library(nycflights13)
library(dplyr)
fleet_lookup <- function(carrier){
carrier_tbl <- flights %>%
select(carrier, tailnum) %>%
distinct()
planes %>%
mutate(manufacturer=recode(manufacturer, "AIRBUS INDUSTRIE"="AIRBUS",
"MCDONNELL DOUGLAS CORPORATION" = "MCDONNELL DOUGLAS",
"MCDONNELL DOUGLAS AIRCRAFT CO" = "MCDONNELL DOUGLAS")) %>%
filter(engine %in% c("Turbo-jet", "Turbo-fan")) %>%
left_join(carrier_tbl) %>%
distinct() %>%
filter( carrier == {{ carrier }}) %>%
group_by(manufacturer, model) %>%
tally() %>%
arrange(desc(n))
}
fleet_lookup("UA")
```
:::
:::
### Plot Fleet Data
Use case: Your data visualization would be valuable to import into multiple reports.
::: columns
::: {.column width="50%"}
```{r}
#| echo: true
#| class-source: longest_code_block
#| classes: longest_code_block
#| eval: false
library(nycflights13)
library(dplyr)
library(ggplot2)
library(ggiraph)
fleet_plot <- function(carrier){
p <- fleet_lookup({{ carrier }}) %>%
ggplot(aes(x=model, y=n, fill = manufacturer)) +
geom_bar_interactive(stat="identity", aes(tooltip = n, data_id = n)) +
theme_minimal() +
theme(legend.position="bottom") +
scale_fill_brewer(palette="Dark2") +
labs(title=paste({{ carrier }},"fleet data from `nycflights13`"),
subtitle="Turbo-fan and Turbo-props only") +
coord_flip()
girafe(code = print(p))
}
fleet_plot("UA")
```
:::
::: {.column width="50%"}
```{r}
#| echo: false
#| class-source: longer_code_block
#| classes: longer_code_block
#| eval: true
library(nycflights13)
library(dplyr)
library(ggplot2)
library(ggiraph)
fleet_plot <- function(carrier){
p <- fleet_lookup({{ carrier }}) %>%
ggplot(aes(x=model, y=n, fill = manufacturer)) +
geom_bar_interactive(stat="identity", aes(tooltip = n, data_id = n)) +
theme_minimal() +
theme(legend.position="bottom") +
scale_fill_brewer(palette="Dark2") +
labs(title=paste({{ carrier }},"fleet data from `nycflights13`"),
subtitle="Turbo-fan and Turbo-props only") +
coord_flip()
girafe(code = print(p))
}
fleet_plot("UA")
```
:::
:::
:::
::: {.notes}
Two additional examples here. What I want to show is one use case where I've got a common data munging and summarization that I'm frequently doing. I have a function where I pull some fleet data, transform and clean it, and summarize it. I'm just pulling data from the `nycflights13` package so clearly not a complete dataset, but it works for illustration. If I input UA, I get a table of the model aircraft arriving and departing NYC airports from the year 2013.
➡️
A second function takes this same concept, but in this case, my function returns a nice interactive plot of my fleet data. In this case, i would be great if I could make this plot readily accessible to other reports in other systems.
So how are we going to do this? Let's walk through it.
:::
## Make an API
```{r}
#| echo: true
#| eval: false
#| classes: longest_code_block
#| class-source: longest_code_block
#| code-line-numbers: "|1|7-8|10|31-33|42-45"
library(plumber)
library(nycflights13)
library(dplyr)
library(ggplot2)
library(ggiraph)
#* @apiTitle Fleet Lookup
#* @apiDescription Plumber example looking up fleet data from `nycflights13`
# Look 👀, I can keep my original function definition as is and I'll just call it below when defining the endpoint.
fleet_lookup <- function(carrier){
carrier_tbl <- flights %>%
select(carrier, tailnum) %>%
distinct()
planes %>%
mutate(manufacturer=recode(manufacturer, "AIRBUS INDUSTRIE"="AIRBUS",
"MCDONNELL DOUGLAS CORPORATION" = "MCDONNELL DOUGLAS",
"MCDONNELL DOUGLAS AIRCRAFT CO" = "MCDONNELL DOUGLAS")) %>%
filter(engine %in% c("Turbo-jet", "Turbo-fan")) %>%
left_join(carrier_tbl) %>%
distinct() %>%
filter( carrier == {{ carrier }}) %>%
group_by(manufacturer, model) %>%
tally() %>%
arrange(desc(n))
}
#* Look up fleet data from the `nycflights13` dataset
#* @param carrier two-letter carrier code
#* @get /fleet_lookup
function(carrier){
fleet_lookup({{carrier}})
}
#* Plot fleet data
#* @serializer htmlwidget
#* @param carrier two-letter carrier code
#* @get /plot
function(carrier){
p <- fleet_lookup({{ carrier }}) %>%
ggplot(aes(x=model, y=n, fill = manufacturer)) +
geom_bar_interactive(stat="identity", aes(tooltip = n, data_id = n)) +
theme_minimal() +
theme(legend.position="bottom") +
scale_fill_brewer(palette="Dark2") +
labs(title=paste({{ carrier }},"fleet data from `nycflights13`"),
subtitle="Turbo-fan and Turbo-props only") +
coord_flip()
girafe(code = print(p))
}
```
::: {.fragment .fade-up}
::: {style="text-align: center;"}
<br>
<h4>✈️ <https://colorado.rstudio.com/rsc/fleet_lookup/></h4>
:::
:::
## What can you do now?
::: panel-tabset
## ModelOps with vetiver
[`vetiver`](vetiver.rstudio.com) simplifies model deployment, cleverly wrapping your model as either a FastAPI or plumber API and pinning it to Connect (or Docker). Easily version your model, monitor metrics, and provide context and documentation with model cards.
![see <https://vetiver.rstudio.com>](https://vetiver.rstudio.com/images/ml_ops_cycle.png){height="500"}
## Integrate with Tableau Analytics Extensions
[`plumbertableau`](https://rstudio.github.io/plumbertableau/) and [`fastapitableau`](https://rstudio.github.io/fastapitableau/) wrap your models or analytics in a Tableau-friendly API format to integrate with the Tableau Analytics Extension.
![see examples at <https://github.com/sol-eng/tableau-examples/>](https://github.com/sol-eng/tableau-examples/raw/main/img/superstore-workbook.png){height="500px\""}
## Parallel Execution
Execute multiple concurrent requests more efficiently within your plumber APIs using `promises` and `future`
![see <https://www.rstudio.com/blog/plumber-v1-1-0/>](https://rstudio.github.io/promises/articles/future_promise/blocked_future_promise.png){height="500px"}
:::
## Calling an API in your data science work
- You can call an API from any system that can formulate a REST-based API request
- In R, use `httr`
```{r}
#| eval: false
library()
response <- GET(query_url) %>%
content(as = "text") %>% jsonlite::fromJSON()
```
- In Python, use `requests`
```{python}
#| eval: false
import requests
response = requests.get(query_url)
```
<br>
More detailed examples at <https://solutions.rstudio.com/r/rest-apis/clients/>
## Resources
* Plumber cheatsheet: <https://rstudio.com/resources/cheatsheets>
* See the `plumber` package website: <https://www.rplumber.io/>. You’ll find installation instructions along with related projects and contextual information
* `plumber` v 1.1.0 included a number of new features, including better support for async calls and new serializers. See <https://www.rstudio.com/blog/plumber-v1-1-0/>
* An excellent webinar covering the Plumber package: <https://rstudio.com/resources/webinars/expanding-r-horizons-integrating-r-with-plumber-apis/>
* If you want to feel inspired, see James Blair's "Democratizing R with Plumber APIs" where he takes an existing Shiny application that uses an R model and turns the model into an API so it can be used by other applications: <https://rstudio.com/resources/rstudioconf-2019/democratizing-r-with-plumber-apis/>
* See Barrett Schloerke's talk "plumber + future: Async Web APIs" from rstudio::global 2021 for asynchronous calls to APIs: <https://www.rstudio.com/resources/rstudioglobal-2021/plumber-and-future-async-web-apis/>
* If you’re interested in how Plumber specifically works with RStudio Connect you can find documentation here: <https://docs.rstudio.com/how-to-guides/rsc/publish-plumberapi/>
## Thank you! {.center .bigger}