---
title: "crul introduction"
author: "Scott Chamberlain"
date: "`r Sys.Date()`"
output: 
  html_document:
    toc: true
    toc_float: true
    theme: readable
vignette: >
  %\VignetteIndexEntry{crul introduction}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r echo=FALSE}
knitr::opts_chunk$set(
  comment = "#>",
  collapse = TRUE,
  warning = FALSE,
  message = FALSE
)
```

`crul` is an HTTP client for R.

## Install

Stable CRAN version

```{r eval=FALSE}
install.packages("crul")
```

Dev version

```{r eval=FALSE}
devtools::install_github("ropensci/crul")
```

```{r}
library("crul")
```

## the client

`HttpClient` is where to start

```{r}
(x <- HttpClient$new(
  url = "https://httpbin.org",
  opts = list(
    timeout = 1
  ),
  headers = list(
    a = "hello world"
  )
))
```

Makes a R6 class, that has all the bits and bobs you'd expect for doing HTTP
requests. When it prints, it gives any defaults you've set. As you update
the object you can see what's been set

```{r}
x$opts
```

```{r}
x$headers
```

## do some http

The client object created above has http methods that you can call,
and pass paths to, as well as query parameters, body values, and any other
curl options.

Here, we'll do a __GET__ request on the route `/get` on our base url
`https://httpbin.org` (the full url is then `https://httpbin.org/get`)

```{r}
res <- x$get("get")
```

The response from a http request is another R6 class `HttpResponse`, which
has slots for the outputs of the request, and some functions to deal with
the response:

Status code

```{r}
res$status_code
```

The content

```{r}
res$content
```

HTTP method

```{r}
res$method
```

Request headers

```{r}
res$request_headers
```

Response headers

```{r}
res$response_headers
```

And you can parse the content with a provided function:

```{r}
res$parse()
jsonlite::fromJSON(res$parse())
```

With the `HttpClient` object, which holds any configuration stuff
we set, we can make other HTTP verb requests. For example, a `HEAD`
request:

```{r}
x$post(
  path = "post", 
  body = list(hello = "world")
)
```


## write to disk

```{r}
x <- HttpClient$new(url = "https://httpbin.org")
f <- tempfile()
res <- x$get(disk = f)
# when using write to disk, content is a path
res$content 
```

Read lines

```{r}
readLines(res$content, n = 10)
```

## stream data

```{r}
(x <- HttpClient$new(url = "https://httpbin.org"))
res <- x$get('stream/5', stream = function(x) cat(rawToChar(x)))
# when streaming, content is NULL
res$content 
```
