Debian Codegraph @

vignettes/intro.Rmd

raw
1 ---
2 title: "The curl package: a modern R interface to libcurl"
3 date: "`r Sys.Date()`"
4 output:
5 html_document:
6 fig_caption: false
7 toc: true
8 toc_float:
9 collapsed: false
10 smooth_scroll: false
11 toc_depth: 3
12 vignette: >
13 %\VignetteIndexEntry{The curl package: a modern R interface to libcurl}
14 %\VignetteEngine{knitr::rmarkdown}
15 %\VignetteEncoding{UTF-8}
16 ---
17
18
19 ```{r, echo = FALSE, message = FALSE}
20 knitr::opts_chunk$set(comment = "")
21 options(width = 120, max.print = 100)
22 wrap.simpleError <- function(x, options) {
23 paste0("```\n## Error: ", x$message, "\n```")
24 }
25 library(curl)
26 library(jsonlite)
27 ```
28
29 The curl package provides bindings to the [libcurl](https://curl.se/libcurl/) C library for R. The package supports retrieving data in-memory, downloading to disk, or streaming using the [R "connection" interface](https://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html). Some knowledge of curl is recommended to use this package. For a more user-friendly HTTP client, have a look at the [httr](https://cran.r-project.org/package=httr/vignettes/quickstart.html) package which builds on curl with HTTP specific tools and logic.
30
31 ## Request interfaces
32
33 The curl package implements several interfaces to retrieve data from a URL:
34
35 - `curl_fetch_memory()` saves response in memory
36 - `curl_download()` or `curl_fetch_disk()` writes response to disk
37 - `curl()` or `curl_fetch_stream()` streams response data
38 - `curl_fetch_multi()` (Advanced) process responses via callback functions
39
40 Each interface performs the same HTTP request, they only differ in how response data is processed.
41
42 ### Getting in memory
43
44 The `curl_fetch_memory` function is a blocking interface which waits for the request to complete and returns a list with all content (data, headers, status, timings) of the server response.
45
46
47 ```{r}
48 req <- curl_fetch_memory("https://hb.cran.dev/get?foo=123")
49 str(req)
50 parse_headers(req$headers)
51 jsonlite::prettify(rawToChar(req$content))
52 ```
53
54 The `curl_fetch_memory` interface is the easiest interface and most powerful for building API clients. However it is not suitable for downloading really large files because it is fully in-memory. If you are expecting 100G of data, you probably need one of the other interfaces.
55
56 ### Downloading to disk
57
58 The second method is `curl_download`, which has been designed as a drop-in replacement for `download.file` in r-base. It writes the response straight to disk, which is useful for downloading (large) files.
59
60 ```{r}
61 tmp <- tempfile()
62 curl_download("https://hb.cran.dev/get?bar=456", tmp)
63 jsonlite::prettify(readLines(tmp))
64 ```
65
66 ### Streaming data
67
68 The most flexible interface is the `curl` function, which has been designed as a drop-in replacement for base `url`. It will create a so-called connection object, which allows for incremental (asynchronous) reading of the response.
69
70 ```{r}
71 con <- curl("https://hb.cran.dev/get")
72 open(con)
73
74 # Get 3 lines
75 out <- readLines(con, n = 3)
76 cat(out, sep = "\n")
77
78 # Get 3 more lines
79 out <- readLines(con, n = 3)
80 cat(out, sep = "\n")
81
82 # Get remaining lines
83 out <- readLines(con)
84 close(con)
85 cat(out, sep = "\n")
86 ```
87
88 The example shows how to use `readLines` on an opened connection to read `n` lines at a time. Similarly `readBin` is used to read `n` bytes at a time for stream parsing binary data.
89
90 #### Non blocking connections
91
92 As of version 2.3 it is also possible to open connections in non-blocking mode. In this case `readBin` and `readLines` will return immediately with data that is available without waiting. For non-blocking connections we use `isIncomplete` to check if the download has completed yet.
93
94 ```{r, eval=FALSE}
95 # This httpbin mirror doesn't cache
96 con <- curl("https://nghttp2.org/httpbin/drip?duration=1&numbytes=50")
97 open(con, "rb", blocking = FALSE)
98 while(isIncomplete(con)){
99 buf <- readBin(con, raw(), 1024)
100 if(length(buf))
101 cat("received: ", rawToChar(buf), "\n")
102 }
103 close(con)
104 ```
105
106 The `curl_fetch_stream` function provides a very simple wrapper around a non-blocking connection.
107
108
109 ### Async requests
110
111 As of `curl 2.0` the package provides an async interface which can perform multiple simultaneous requests concurrently. The `curl_fetch_multi` adds a request to a pool and returns immediately; it does not actually perform the request.
112
113 ```{r}
114 pool <- new_pool()
115 success <- function(req){cat("success:", req$url, ": HTTP:", req$status, "\n")}
116 failure <- function(err){cat("failure:", err, "\n")}
117 curl_fetch_multi('https://www.google.com', done = success, fail = failure, pool = pool)
118 curl_fetch_multi('https://cloud.r-project.org', done = success, fail = failure, pool = pool)
119 curl_fetch_multi('https://hb.cran.dev/blabla', done = success, fail = failure, pool = pool)
120 curl_fetch_multi('https://doesnotexit.xyz', done = success, fail = failure, pool = pool)
121 ```
122
123 When we call `multi_run()`, all scheduled requests are performed concurrently. The callback functions get triggered when each request completes.
124
125 ```{r}
126 # This actually performs requests:
127 out <- multi_run(pool = pool)
128 print(out)
129 ```
130
131 The system allows for running many concurrent non-blocking requests. However it is quite complex and requires careful specification of handler functions.
132
133 ## Exception handling
134
135 A HTTP requests can encounter two types of errors:
136
137 1. Connection failure: network down, host not found, invalid SSL certificate, etc
138 2. HTTP non-success status: 401 (DENIED), 404 (NOT FOUND), 503 (SERVER PROBLEM), etc
139
140 The first type of errors (connection failures) will always raise an error in R for each interface. However if the requests succeeds and the server returns a non-success HTTP status code, only `curl()` and `curl_download()` will raise an error. Let's dive a little deeper into this.
141
142 ### Error automatically
143
144 The `curl` and `curl_download` functions are safest to use because they automatically raise an error if the request was completed but the server returned a non-success (400 or higher) HTTP status. This mimics behavior of base functions `url` and `download.file`. Therefore we can safely write code like this:
145
146 ```{r}
147 # This is OK
148 curl_download('https://cloud.r-project.org/CRAN_mirrors.csv', 'mirrors.csv')
149 mirros <- read.csv('mirrors.csv')
150 unlink('mirrors.csv')
151 ```
152
153 If the HTTP request was unsuccessful, R will not continue:
154
155 ```{r, error=TRUE}
156 # Oops! A typo in the URL!
157 curl_download('https://cloud.r-project.org/CRAN_mirrorZ.csv', 'mirrors.csv')
158 con <- curl('https://cloud.r-project.org/CRAN_mirrorZ.csv')
159 open(con)
160 ```
161
162 ```{r, echo = FALSE, message = FALSE, warning=FALSE}
163 close(con)
164 rm(con)
165 ```
166
167
168 ### Check manually
169
170 When using any of the `curl_fetch_*` functions it is important to realize that these do **not** raise an error if the request was completed but returned a non-200 status code. When using `curl_fetch_memory` or `curl_fetch_disk` you need to implement such application logic yourself and check if the response was successful.
171
172 ```{r}
173 req <- curl_fetch_memory('https://cloud.r-project.org/CRAN_mirrors.csv')
174 print(req$status_code)
175 ```
176
177 Same for downloading to disk. If you do not check your status, you might have downloaded an error page!
178
179 ```{r}
180 # Oops a typo!
181 req <- curl_fetch_disk('https://cloud.r-project.org/CRAN_mirrorZ.csv', 'mirrors.csv')
182 print(req$status_code)
183
184 # This is not the CSV file we were expecting!
185 head(readLines('mirrors.csv'))
186 unlink('mirrors.csv')
187 ```
188
189 If you *do* want the `curl_fetch_*` functions to automatically raise an error, you should set the [`FAILONERROR`](https://curl.se/libcurl/c/CURLOPT_FAILONERROR.html) option to `TRUE` in the handle of the request.
190
191 ```{r, error=TRUE}
192 h <- new_handle(failonerror = TRUE)
193 curl_fetch_memory('https://cloud.r-project.org/CRAN_mirrorZ.csv', handle = h)
194 ```
195
196 ## Customizing requests
197
198 By default libcurl uses HTTP GET to issue a request to an HTTP url. To send a customized request, we first need to create and configure a curl handle object that is passed to the specific download interface.
199
200 ### Setting handle options
201
202 Creating a new handle is done using `new_handle`. After creating a handle object, we can set the libcurl options and http request headers.
203
204 ```{r}
205 h <- new_handle()
206 handle_setopt(h, copypostfields = "moo=moomooo");
207 handle_setheaders(h,
208 "Content-Type" = "text/moo",
209 "Cache-Control" = "no-cache",
210 "User-Agent" = "A cow"
211 )
212 ```
213
214 Use the `curl_options()` function to get a list of the options supported by your version of libcurl. The [libcurl documentation](https://curl.se/libcurl/c/curl_easy_setopt.html) explains what each option does. Option names are not case sensitive.
215
216 It is important you check the [libcurl documentation](https://curl.se/libcurl/c/curl_easy_setopt.html) to set options of the correct type. Options in libcurl take several types:
217
218 - number
219 - string
220 - slist (vector of strings)
221 - enum (long) option
222
223 The R bindings will automatically do some type checking and coercion to convert R values to appropriate libcurl option values. Logical (boolean) values in R automatically get converted to `0` or `1` for example [CURLOPT_VERBOSE](https://curl.se/libcurl/c/CURLOPT_VERBOSE.html):
224
225
226 ```{r}
227 handle <- new_handle(verbose = TRUE)
228 ```
229
230 However R does not know if an option is actually boolean. So passing `TRUE`/ `FALSE` to any numeric option will simply set it to `0` or `1` without a warning or error. If an option value cannot be coerced, you get an error:
231
232 ```{r, error = TRUE}
233 # URLOPT_MASFILESIZE must be a number
234 handle_setopt(handle, maxfilesize = "foo")
235
236 # CURLOPT_USERAGENT must be a string
237 handle_setopt(handle, useragent = 12345)
238 ```
239
240
241 ### ENUM (long) options
242
243 Some curl options take an long in C that actually corresponds to an ENUM value.
244
245 For example the [CURLOPT_USE_SSL](https://curl.se/libcurl/c/CURLOPT_USE_SSL.html) docs explains that there are 4 possible values for this option: `CURLUSESSL_NONE`, `CURLUSESSL_TRY`, `CURLUSESSL_CONTROL`, and `CURLUSESSL_ALL`. To use this option you have to lookup the integer values for these enums in the symbol table. These symbol values never change, so you only need to lookup the value you need once and then hardcode the integer value in your R code.
246
247 ```{r}
248 curl::curl_symbols("CURLUSESSL")
249 ```
250
251 So suppose we want to set `CURLOPT_USE_SSL` to `CURLUSESSL_ALL` we would use this R code:
252
253 ```{r}
254 handle_setopt(handle, use_ssl = 3)
255 ```
256
257 ### Disabling HTTP/2
258
259 Another example is the [CURLOPT_HTTP_VERSION](https://curl.se/libcurl/c/CURLOPT_HTTP_VERSION.html) option. This option is needed to disable or enable HTTP/2. However some users are not aware this is actually an ENUM and not a regular numeric value!
260
261 The [docs](https://curl.se/libcurl/c/CURLOPT_HTTP_VERSION.html) explain HTTP_VERSION can be set to one of several strategies for negotiating the HTTP version between client and server. Valid values are:
262
263 ```{r}
264 curl_symbols('CURL_HTTP_VERSION_')
265 ```
266
267 As seen, the value `2` corresponds to `CURL_HTTP_VERSION_1_1` and `3` corresponds to `CURL_HTTP_VERSION_2_0`.
268
269 As of libcurl 7.62.0, the default `http_version` is `CURL_HTTP_VERSION_2TLS` which uses HTTP/2 when possible, but only for HTTPS connections. Package authors should usually leave the default to let curl select the best appropriate http protocol.
270
271 One exception is when writing a client for a server that seems to be running a buggy HTTP/2 server. Unfortunately this is not uncommon, and curl is a bit more picky than browsers. If you are frequently seeing `Error in the HTTP2 framing layer` error messages, then there is likely a problem with the HTTP/2 layer on the server.
272
273 The easiest remedy is to __disable http/2__ for this server by forcing http 1.1 until the service has upgraded their webservers. To do so, set the `http_version` to `CURL_HTTP_VERSION_1_1` (value: `2`):
274
275 ```{r}
276 # Force using HTTP 1.1 (the number 2 is an enum value, see above)
277 handle_setopt(handle, http_version = 2)
278 ```
279
280 Note that the value `1` corresponds to HTTP 1.0 which is a legacy version of HTTP that you should not use!
281 Code that sets `http_version` to `1` (or even `1.1` which R simply rounds to 1) is almost always a bug.
282
283 ## Performing the request
284
285 After the handle has been configured, it can be used with any of the download interfaces to perform the request. For example `curl_fetch_memory` will load store the output of the request in memory:
286
287 ```{r}
288 req <- curl_fetch_memory("https://hb.cran.dev/post", handle = h)
289 jsonlite::prettify(rawToChar(req$content))
290 ```
291
292 Alternatively we can use `curl()` to read the data of via a connection interface:
293
294 ```{r}
295 con <- curl("https://hb.cran.dev/post", handle = h)
296 jsonlite::prettify(readLines(con))
297 ```
298
299 ```{r, echo = FALSE, message = FALSE, warning=FALSE}
300 close(con)
301 ```
302
303 Or we can use `curl_download` to write the response to disk:
304
305 ```{r}
306 tmp <- tempfile()
307 curl_download("https://hb.cran.dev/post", destfile = tmp, handle = h)
308 jsonlite::prettify(readLines(tmp))
309 ```
310
311 Or perform the same request with a multi pool:
312
313 ```{r}
314 curl_fetch_multi("https://hb.cran.dev/post", handle = h, done = function(res){
315 cat("Request complete! Response content:\n")
316 cat(rawToChar(res$content))
317 })
318
319 # Perform the request
320 out <- multi_run()
321 ```
322
323 ### Reading cookies
324
325 Curl handles automatically keep track of cookies set by the server. At any given point we can use `handle_cookies` to see a list of current cookies in the handle.
326
327 ```{r}
328 # Start with a fresh handle
329 h <- new_handle()
330
331 # Ask server to set some cookies
332 req <- curl_fetch_memory("https://hb.cran.dev/cookies/set?foo=123&bar=ftw", handle = h)
333 req <- curl_fetch_memory("https://hb.cran.dev/cookies/set?baz=moooo", handle = h)
334 handle_cookies(h)
335
336 # Unset a cookie
337 req <- curl_fetch_memory("https://hb.cran.dev/cookies/delete?foo", handle = h)
338 handle_cookies(h)
339 ```
340
341 The `handle_cookies` function returns a data frame with 7 columns as specified in the [netscape cookie file format](http://www.cookiecentral.com/faq/#3.5).
342
343 ### On reusing handles
344
345 In most cases you should not re-use a single handle object for more than one request. The only benefit of reusing a handle for multiple requests is to keep track of cookies set by the server (seen above). This could be needed if your server uses session cookies, but this is rare these days. Most APIs set state explicitly via http headers or parameters, rather than implicitly via cookies.
346
347 In recent versions of the curl package there are no performance benefits of reusing handles. The overhead of creating and configuring a new handle object is negligible. The safest way to issue multiple requests, either to a single server or multiple servers is by using a separate handle for each request (which is the default)
348
349 ```{r}
350 req1 <- curl_fetch_memory("https://hb.cran.dev/get")
351 req2 <- curl_fetch_memory("https://www.google.com")
352 ```
353
354 In past versions of this package you needed to manually use a handle to take advantage of http Keep-Alive. However as of version 2.3 this is no longer the case: curl automatically maintains global a pool of open http connections shared by all handles. When performing many requests to the same server, curl automatically uses existing connections when possible, eliminating TCP/SSL handshaking overhead:
355
356 ```{r}
357 req <- curl_fetch_memory("https://api.github.com/users/ropensci")
358 req$times
359
360 req2 <- curl_fetch_memory("https://api.github.com/users/rstudio")
361 req2$times
362 ```
363
364 If you really need to re-use a handle, do note that that curl does not cleanup the handle after each request. All of the options and internal fields will linger around for all future request until explicitly reset or overwritten. This can sometimes leads to unexpected behavior.
365
366 ```{r}
367 handle_reset(h)
368 ```
369
370 The `handle_reset` function will reset all curl options and request headers to the default values. It will **not** erase cookies and it will still keep alive the connections. Therefore it is good practice to call `handle_reset` after performing a request if you want to reuse the handle for a subsequent request. Still it is always safer to create a new fresh handle when possible, rather than recycling old ones.
371
372 ### Posting forms
373
374 The `handle_setform` function is used to perform a `multipart/form-data` HTTP POST request (a.k.a. posting a form). Values can be either strings, raw vectors (for binary data) or files.
375
376 ```{r}
377 # Posting multipart
378 h <- new_handle()
379 handle_setform(h,
380 foo = "blabla",
381 bar = charToRaw("boeboe"),
382 iris = form_data(serialize(iris, NULL), "application/rda"),
383 description = form_file(system.file("DESCRIPTION")),
384 logo = form_file(file.path(R.home('doc'), "html/logo.jpg"), "image/jpeg")
385 )
386 req <- curl_fetch_memory("https://hb.cran.dev/post", handle = h)
387 ```
388
389 The `form_file` function is used to upload files with the form post. It has two arguments: a file path, and optionally a content-type value. If no content-type is set, curl will guess the content type of the file based on the file extension.
390
391 The `form_data` function is similar but simply posts a string or raw value with a custom content-type.
392
393 ### Using pipes
394
395 All of the `handle_xxx` functions return the handle object so that function calls can be chained using the popular pipe operators:
396
397 ```{r eval=getRversion() > "4.1"}
398 # Perform request
399 res <- new_handle() |>
400 handle_setopt(copypostfields = "moo=moomooo") |>
401 handle_setheaders("Content-Type"="text/moo", "Cache-Control"="no-cache", "User-Agent"="A cow") |>
402 curl_fetch_memory(url = "https://hb.cran.dev/post")
403
404 # Parse response
405 res$content |> rawToChar() |> jsonlite::prettify()
406 ```