Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/bergant/rapiclient

Dynamic Open API (Swagger) Client for R
https://github.com/bergant/rapiclient

api openapi r swagger

Last synced: 8 days ago
JSON representation

Dynamic Open API (Swagger) Client for R

Awesome Lists containing this project

README

        

---
output:
html_document:
keep_md: yes
---

# __rapiclient__

[![Build Status](https://travis-ci.org/bergant/rapiclient.svg?branch=master)](https://travis-ci.org/bergant/rapiclient)
[![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/rapiclient)](http://cran.r-project.org/package=rapiclient)

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

Access services specified in [OpenAPI](https://openapis.org) (formerly Swagger) format.

**rapiclient** is not a code generator. Client is generated dynamically as
a list of R functions.

## Installation
Install the current released version from CRAN:

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

Or get the current development version from github:

```{r eval=FALSE}
# install.packages("devtools")
devtools::install_github("bergant/rapiclient")
```

## Usage

### Prepare API Operations and Schemas

```{r}
library(rapiclient)
```

This example uses the [sample petstore service](http://petstore.swagger.io)
and its OpenAPI definition at (http://petstore.swagger.io/v2/swagger.json).

```{r api, cache=TRUE}
pet_api <- get_api(url = "http://petstore.swagger.io/v2/swagger.json")
operations <- get_operations(pet_api)
schemas <- get_schemas(pet_api)
```

Function `get_operations` returns a **list of functions**.
Each function takes named arguments, converts the values to JSON
according to API operation definition and performs a service call which
returns a http response object.

Function `get_schemas` returns a list of functions where each function returns
an object according to the related schema in the API.

### Calling Service Operations

#### Find a Pet
Let's try to find a pet with Id = 42 (see operation [definition](http://petstore.swagger.io/#!/pet/getPetById)):
```{r getPetById, cache=TRUE}
res <- operations$getPetById(petId = 42)

res$status_code
str(httr::content(res))
```

#### New Pet
OK, there is no pet with Id = 42, so let's [add a pet](http://petstore.swagger.io/#!/pet/addPet):

```{r addPet, cache=TRUE}
res <-
operations$addPet(
id = 42,
category = schemas$Category(
id = 1,
name = "Undefined"
),
name = "Agrajag",
photoUrls = list(),
tags = list(
schemas$Tag(id = 1, name = "Wild"),
schemas$Tag(id = 2, name = "Furry")
),
status = "available"
)

res$status_code
```

Check:

```{r findPet2, cache=TRUE}
res <- operations$getPetById(petId = 42)

res$status_code
str(httr::content(res))
```

### Response Handlers

If all operations are handled identically (e.g. reading content or stop
on http exception), it is more convenient to create the API functions
with this functionality. `get_operations` accepts an optional handler
function which must accept a httr response object as an argument.

Some handler functions are already predefined. For example `content_or_stop`
returns a content or throws an exception.

```{r, cache = TRUE}
operations <- get_operations(pet_api, handle_response = content_or_stop)

pet_data <- operations$getPetById(42)
str(pet_data)
```

Note that you can always trace the communication between client and server with `httr::with_verbose`:

```{r, eval=FALSE, echo = TRUE}
httr::with_verbose({
# get pet data
pet_data <- operations$getPetById(42)
# delete a pet entry
operations$deletePet(api_key = "special-key", petId = 42)
})
```

```{r, cache=TRUE, eval = TRUE, echo=FALSE}
cat(capture.output(type = "message",

httr::with_verbose({
# get pet data
pet_data <- operations$getPetById(42)
# delete a pet entry
operations$deletePet(api_key = "special-key", petId = 42)
})

))
```

### Help on API Operations

The good news is that autocomplete in RStudio editor works fine with dynamically created functions. The bad news: R documentation is not available
with `help` or `?`. To lookup the operation definition
just print the function (write it down without parenthesis):

Let's get help for `getPetById`:
```{r print}
operations$getPetById
```

More complicated `addPet` also describes the nested schemas:

```{r print2}
operations$addPet
```

For more detailed operation description use the operation's "definition" attribute :

```{r operation_definition}
definition <- attr(operations$getPetById, "definition")
str(definition)
```

### Using Additional Headers

Set additional http headers at the time of creating operation functions
in `get_operations` function.

The following example uses New York Times API from [developer.nytimes.com](http://developer.nytimes.com/)
with API key authentication.

```{r nyt_api_test, cache=TRUE}
nyt_api <- get_api("http://developer.nytimes.com/top_stories_v2.json/swagger.json")

nyt_operations <-
get_operations( nyt_api, .headers = c("api-key" = Sys.getenv("NYT_API_KEY")))

res <- nyt_operations$Top_Stories(section = "science", format = "json")

res$status_code

content <- httr::content(res)
str(content, max.level = 1)

```