[R] add streaming support (#12821)

* add streaming option to r client

* support callback function to process data stream

* add stream test, minor bug fixes

* fix api client

* return void earlier if streaming, add tests
This commit is contained in:
William Cheng
2022-07-11 00:19:07 +08:00
committed by GitHub
parent 84ac06abdc
commit 20420e5e14
11 changed files with 488 additions and 114 deletions

View File

@@ -224,11 +224,9 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
additionalProperties.put(CodegenConstants.EXCEPTION_ON_FAILURE, returnExceptionOnFailure);
additionalProperties.put(USE_DEFAULT_EXCEPTION, this.useDefaultExceptionHandling);
additionalProperties.put(USE_RLANG_EXCEPTION, this.useRlangExceptionHandling);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);

View File

@@ -177,14 +177,23 @@
{{#optionalParams}}
#' @param {{{paramName}}} (optional) {{{description}}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}}
{{/optionalParams}}
{{#vendorExtensions.x-streaming}}
#' @param stream_callback (optional) callback function to process the data stream
{{/vendorExtensions.x-streaming}}
{{#returnType}}
#' @param data_file (optional) name of the data file to save the result
{{/returnType}}
#' @param ... Other optional arguments
#' @return {{{returnType}}}{{^returnType}}void{{/returnType}}
#' @export
{{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file=NULL, {{/returnType}}...) {
api_response <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}{{#returnType}}data_file = data_file, {{/returnType}}...)
{{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback=NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file=NULL, {{/returnType}}...) {
api_response <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}{{#vendorExtensions.x-streaming}}stream_callback = stream_callback, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = data_file, {{/returnType}}...)
{{#vendorExtensions.x-streaming}}
if (typeof(stream_callback) == "closure") { # return void if streaming is enabled
return(invisible(NULL))
}
{{/vendorExtensions.x-streaming}}
resp <- api_response$response
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
api_response$content
@@ -207,13 +216,16 @@
{{#optionalParams}}
#' @param {{{paramName}}} (optional) {{{description}}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}}
{{/optionalParams}}
{{#vendorExtensions.x-streaming}}
#' @param stream_callback (optional) callback function to process the data stream
{{/vendorExtensions.x-streaming}}
{{#returnType}}
#' @param data_file (optional) name of the data file to save the result
{{/returnType}}
#' @param ... Other optional arguments
#' @return API response ({{{returnType}}}{{^returnType}}void{{/returnType}}) with additional information such as HTTP status code, headers
#' @export
{{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file = NULL, {{/returnType}}...) {
{{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback=NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = NULL, {{/returnType}}...) {
args <- list(...)
query_params <- list()
header_params <- c()
@@ -311,8 +323,17 @@
query_params = query_params,
header_params = header_params,
body = body,
{{#vendorExtensions.x-streaming}}
stream_callback = stream_callback,
{{/vendorExtensions.x-streaming}}
...)
{{#vendorExtensions.x-streaming}}
if (typeof(stream_callback) == "closure") { # return void if streaming is enabled
return(invisible(NULL))
}
{{/vendorExtensions.x-streaming}}
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
{{#returnType}}
{{#isPrimitiveType}}

View File

@@ -128,9 +128,9 @@ ApiClient <- R6::R6Class(
#' @param ... Other optional arguments.
#' @return HTTP response
#' @export
CallApi = function(url, method, query_params, header_params, body, ...) {
CallApi = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) {
resp <- self$Execute(url, method, query_params, header_params, body, ...)
resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...)
status_code <- httr::status_code(resp)
if (is.null(self$max_retry_attempts)) {
@@ -142,7 +142,7 @@ ApiClient <- R6::R6Class(
for (i in 1 : self$max_retry_attempts) {
if (status_code %in% self$retry_status_codes) {
Sys.sleep((2 ^ i) + stats::runif(n = 1, min = 0, max = 1))
resp <- self$Execute(url, method, query_params, header_params, body, ...)
resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...)
status_code <- httr::status_code(resp)
} else {
break;
@@ -162,10 +162,11 @@ ApiClient <- R6::R6Class(
#' @param query_params The query parameters.
#' @param header_params The header parameters.
#' @param body The HTTP request body.
#' @param stream_callback callback function to process data stream
#' @param ... Other optional arguments.
#' @return HTTP response
#' @export
Execute = function(url, method, query_params, header_params, body, ...) {
Execute = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) {
headers <- httr::add_headers(c(header_params, self$default_headers))
{{! Adding timeout that can be set at the apiClient object level}}
@@ -175,17 +176,41 @@ ApiClient <- R6::R6Class(
}
if (method == "GET") {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "POST") {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "PUT") {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "PATCH") {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "HEAD") {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "DELETE") {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else {
err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`."
{{#useDefaultExceptionHandling}}

View File

@@ -53,7 +53,7 @@ result <- tryCatch(
# to save the result into a file, simply add the optional `data_file` parameter, e.g.
# api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}data_file = "result.txt"),
{{/returnType}}
api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}),
api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#vendorExtensions.x-streaming}}, stream_callback = function(x){ print(length(x)) }{{/vendorExtensions.x-streaming}}),
ApiException = function(ex) ex
)
# In case of error, print the error object

View File

@@ -185,6 +185,38 @@ paths:
description: Pet not found
security:
- api_key: []
'/pet/{petId}?streaming':
get:
tags:
- pet
summary: Find pet by ID (streaming)
description: Returns a single pet
operationId: getPetByIdStreaming
x-streaming: true
parameters:
- name: petId
in: path
description: ID of pet to return
required: true
schema:
type: integer
format: int64
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
security:
- api_key: []
post:
tags:
- pet

View File

@@ -133,9 +133,9 @@ ApiClient <- R6::R6Class(
#' @param ... Other optional arguments.
#' @return HTTP response
#' @export
CallApi = function(url, method, query_params, header_params, body, ...) {
CallApi = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) {
resp <- self$Execute(url, method, query_params, header_params, body, ...)
resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...)
status_code <- httr::status_code(resp)
if (is.null(self$max_retry_attempts)) {
@@ -147,7 +147,7 @@ ApiClient <- R6::R6Class(
for (i in 1 : self$max_retry_attempts) {
if (status_code %in% self$retry_status_codes) {
Sys.sleep((2 ^ i) + stats::runif(n = 1, min = 0, max = 1))
resp <- self$Execute(url, method, query_params, header_params, body, ...)
resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...)
status_code <- httr::status_code(resp)
} else {
break;
@@ -167,10 +167,11 @@ ApiClient <- R6::R6Class(
#' @param query_params The query parameters.
#' @param header_params The header parameters.
#' @param body The HTTP request body.
#' @param stream_callback callback function to process data stream
#' @param ... Other optional arguments.
#' @return HTTP response
#' @export
Execute = function(url, method, query_params, header_params, body, ...) {
Execute = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) {
headers <- httr::add_headers(c(header_params, self$default_headers))
http_timeout <- NULL
@@ -179,17 +180,41 @@ ApiClient <- R6::R6Class(
}
if (method == "GET") {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "POST") {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "PUT") {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "PATCH") {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "HEAD") {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else if (method == "DELETE") {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
if (typeof(stream_callback) == "closure") {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...)
} else {
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
}
} else {
err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`."
rlang::abort(message = err_msg, .subclass = "ApiException", ApiException = ApiException$new(status = 0, reason = err_msg))

View File

@@ -139,6 +139,38 @@
#' }
#' }
#'
#' \strong{ GetPetByIdStreaming } \emph{ Find pet by ID (streaming) }
#' Returns a single pet
#'
#' \itemize{
#' \item \emph{ @param } pet_id integer
#' \item \emph{ @returnType } \link{Pet} \cr
#'
#' \item On encountering errors, an error of subclass ApiException will be thrown.
#'
#' \item status code : 200 | successful operation
#'
#' \item return type : Pet
#' \item response headers :
#'
#' \tabular{ll}{
#' }
#' \item status code : 400 | Invalid ID supplied
#'
#'
#' \item response headers :
#'
#' \tabular{ll}{
#' }
#' \item status code : 404 | Pet not found
#'
#'
#' \item response headers :
#'
#' \tabular{ll}{
#' }
#' }
#'
#' \strong{ UpdatePet } \emph{ Update an existing pet }
#'
#'
@@ -361,6 +393,34 @@
#' }
#'
#'
#' #################### GetPetByIdStreaming ####################
#'
#' library(petstore)
#' var.pet_id <- 56 # integer | ID of pet to return
#'
#' #Find pet by ID (streaming)
#' api.instance <- PetApi$new()
#'
#' #Configure API key authorization: api_key
#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY';
#'
#'result <- tryCatch(
#' api.instance$GetPetByIdStreaming(var.pet_id),
#' ApiException = function(ex) ex
#' )
#' # In case of error, print the error object
#' if(!is.null(result$ApiException)) {
#' cat(result$ApiException$toString())
#' } else {
#' # deserialized response object
#' response.object <- result$content
#' # response headers
#' response.headers <- result$response$headers
#' # response status code
#' response.status.code <- result$response$status_code
#' }
#'
#'
#' #################### UpdatePet ####################
#'
#' library(petstore)
@@ -606,7 +666,7 @@ PetApi <- R6::R6Class(
}
body <- NULL
url_path <- "/pet/{petId}"
url_path <- "/pet/{petId}?streaming"
if (!missing(`pet_id`)) {
url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path)
}
@@ -910,6 +970,110 @@ PetApi <- R6::R6Class(
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
}
},
#' Find pet by ID (streaming)
#'
#' @description
#' Find pet by ID (streaming)
#'
#' @param pet_id ID of pet to return
#' @param stream_callback (optional) callback function to process the data stream
#' @param data_file (optional) name of the data file to save the result
#' @param ... Other optional arguments
#' @return Pet
#' @export
GetPetByIdStreaming = function(pet_id, stream_callback=NULL, data_file=NULL, ...) {
api_response <- self$GetPetByIdStreamingWithHttpInfo(pet_id, stream_callback = stream_callback, data_file = data_file, ...)
if (typeof(stream_callback) == "closure") { # return void if streaming is enabled
return(invisible(NULL))
}
resp <- api_response$response
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
api_response$content
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
api_response
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
api_response
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
api_response
}
},
#' Find pet by ID (streaming)
#'
#' @description
#' Find pet by ID (streaming)
#'
#' @param pet_id ID of pet to return
#' @param stream_callback (optional) callback function to process the data stream
#' @param data_file (optional) name of the data file to save the result
#' @param ... Other optional arguments
#' @return API response (Pet) with additional information such as HTTP status code, headers
#' @export
GetPetByIdStreamingWithHttpInfo = function(pet_id, stream_callback=NULL, data_file = NULL, ...) {
args <- list(...)
query_params <- list()
header_params <- c()
if (missing(`pet_id`)) {
rlang::abort(message = "Missing required parameter `pet_id`.", .subclass = "ApiException", ApiException = ApiException$new(status = 0, reason = "Missing required parameter `pet_id`."))
}
body <- NULL
url_path <- "/pet/{petId}?streaming"
if (!missing(`pet_id`)) {
url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path)
}
# API key authentication
if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) {
header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "")
}
resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path),
method = "GET",
query_params = query_params,
header_params = header_params,
body = body,
stream_callback = stream_callback,
...)
if (typeof(stream_callback) == "closure") { # return void if streaming is enabled
return(invisible(NULL))
}
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
# save response in a file
if (!is.null(data_file)) {
write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file)
}
deserialized_resp_obj <- tryCatch(
self$api_client$deserialize(resp, "Pet", loadNamespace("petstore")),
error = function(e) {
rlang::abort(message = "Failed to deserialize response", .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
}
)
ApiResponse$new(deserialized_resp_obj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.")
}
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- "Api client exception encountered."
}
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- "Api server exception encountered."
}
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
}
},
#' Update an existing pet
#'
#' @description
@@ -1051,7 +1215,7 @@ PetApi <- R6::R6Class(
"status" = status
)
url_path <- "/pet/{petId}"
url_path <- "/pet/{petId}?streaming"
if (!missing(`pet_id`)) {
url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path)
}

View File

@@ -63,12 +63,13 @@ Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*FakeApi* | [**FakeDataFile**](docs/FakeApi.md#FakeDataFile) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly
*PetApi* | [**AddPet**](docs/PetApi.md#AddPet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#DeletePet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**DeletePet**](docs/PetApi.md#DeletePet) | **DELETE** /pet/{petId}?streaming | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#FindPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#FindPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#GetPetById) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**GetPetByIdStreaming**](docs/PetApi.md#GetPetByIdStreaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming)
*PetApi* | [**UpdatePet**](docs/PetApi.md#UpdatePet) | **PUT** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId}?streaming | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#UploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#DeleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#GetInventory) | **GET** /store/inventory | Returns pet inventories by status

View File

@@ -5,12 +5,13 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**AddPet**](PetApi.md#AddPet) | **POST** /pet | Add a new pet to the store
[**DeletePet**](PetApi.md#DeletePet) | **DELETE** /pet/{petId} | Deletes a pet
[**DeletePet**](PetApi.md#DeletePet) | **DELETE** /pet/{petId}?streaming | Deletes a pet
[**FindPetsByStatus**](PetApi.md#FindPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
[**FindPetsByTags**](PetApi.md#FindPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
[**GetPetById**](PetApi.md#GetPetById) | **GET** /pet/{petId} | Find pet by ID
[**GetPetByIdStreaming**](PetApi.md#GetPetByIdStreaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming)
[**UpdatePet**](PetApi.md#UpdatePet) | **PUT** /pet | Update an existing pet
[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId}?streaming | Updates a pet in the store with form data
[**UploadFile**](PetApi.md#UploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
@@ -317,6 +318,68 @@ Name | Type | Description | Notes
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
# **GetPetByIdStreaming**
> Pet GetPetByIdStreaming(pet_id)
Find pet by ID (streaming)
Returns a single pet
### Example
```R
library(petstore)
var_pet_id <- 56 # integer | ID of pet to return
#Find pet by ID (streaming)
api_instance <- PetApi$new()
# Configure API key authorization: api_key
api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY';
result <- tryCatch(
# to save the result into a file, simply add the optional `data_file` parameter, e.g.
# api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"),
api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x){ print(length(x)) }),
ApiException = function(ex) ex
)
# In case of error, print the error object
if (!is.null(result$ApiException)) {
cat(result$ApiException$toString())
} else {
# deserialized response object
response.object <- result$content
# response headers
response.headers <- result$response$headers
# response status code
response.status.code <- result$response$status_code
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**pet_id** | **integer**| ID of pet to return |
### Return type
[**Pet**](Pet.md)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
# **UpdatePet**
> Pet UpdatePet(pet)

View File

@@ -2,25 +2,35 @@
install.packages("petstore_1.0.0.tar.gz",repos=NULL, type="source")
library(petstore)
#errorMsg <- "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}"
##errorMsg <- '{"code": 404, "message": "Not found"}'
#a <- ModelApiResponse$new()$fromJSONString(errorMsg)
#dput(a)
#
#var_pet_id <- 1231256 # integer | ID of pet to return
#
##Find pet by ID
#api_instance <- PetApi$new()
## Configure API key authorization: api_key
#api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY';
#result <- tryCatch(
# api_instance$GetPetById(var_pet_id),
# ApiException = function(ex) ex
# )
## In case of error, print the error object
#if(!is.null(result$ApiException)) {
var_pet <- Pet$new("name_example", list("photoUrls_example"), 56, Category$new(56, "name_example"), list(Tag$new(56, "name_example")), "available") # Pet | Pet object that needs to be added to the store
#Add a new pet to the store
api_instance <- PetApi$new()
# Configure OAuth2 access token for authorization: petstore_auth
api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN';
result <- tryCatch(
# to save the result into a file, simply add the optional `data_file` parameter, e.g.
# api_instance$AddPet(var_pet, data_file = "result.txt"),
api_instance$AddPet(var_pet),
ApiException = function(ex) ex
)
var_pet_id <- 56 # integer | ID of pet to return
#Find pet by ID (streaming)
api_instance <- PetApi$new()
# Configure API key authorization: api_key
api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY';
result <- tryCatch(
# to save the result into a file, simply add the optional `data_file` parameter, e.g.
# api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"),
api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x) { print(x) }),
ApiException = function(ex) ex
)
# In case of error, print the error object
#if (!is.null(result$ApiException)) {
# cat(result$ApiException$toString())
#} else {
#} #else {
# # deserialized response object
# response.object <- result$content
# # response headers
@@ -29,75 +39,103 @@ library(petstore)
# response.status.code <- result$response$status_code
#}
json2 <-
'{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}'
jsonlite::minify(json2)
pet_api <- PetApi$new()
pet_id <- 123321
pet <- Pet$new("name_test",
photoUrls = list("photo_test", "second test"),
category = Category$new(id = 450, name = "test_cat"),
id = pet_id,
tags = list(
Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")
),
status = "available"
)
#jsonlite::minify(pet$toJSONString())
#cat(pet$toJSONString())
toString(pet$toString())
#json <-
#'[
# {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"},
# {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"},
# {},
# {"Name" : "Bowser", "Occupation" : "Koopa"}
#]'
##errorMsg <- "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}"
###errorMsg <- '{"code": 404, "message": "Not found"}'
##a <- ModelApiResponse$new()$fromJSONString(errorMsg)
##dput(a)
##
##var_pet_id <- 1231256 # integer | ID of pet to return
##
###Find pet by ID
##api_instance <- PetApi$new()
### Configure API key authorization: api_key
##api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY';
##result <- tryCatch(
## api_instance$GetPetById(var_pet_id),
## ApiException = function(ex) ex
## )
### In case of error, print the error object
##if(!is.null(result$ApiException)) {
## cat(result$ApiException$toString())
##} else {
## # deserialized response object
## response.object <- result$content
## # response headers
## response.headers <- result$response$headers
## # response status code
## response.status.code <- result$response$status_code
##}
#
#json2 <-
#'{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}'
#
##Pet$public_methods
##Pet$public_methods$fromJSON(json)
##Pet$public_methods$toJson()
##Pet$public_methods$validateJSON(json2)
##Pet$public_methods$validateJson(json)
##Pet$my_static_method <- function(x) { x + 2}
##Pet$public_methods$my_static_method(1)
#jsonlite::minify(json2)
#
basque_pig_json <-
'{"className2": "BasquePig", "color": "red"}'
#
# danish_pig_json <-
# '{"className2": "DanishPig", "size": 7}'
#
# wrong_json <-
# '[
# {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"},
# {},
# {"Name" : "Ada", "Occupation" : "Engineer"}
# ]'
#pet_api <- PetApi$new()
#pet_id <- 123321
#pet <- Pet$new("name_test",
# photoUrls = list("photo_test", "second test"),
# category = Category$new(id = 450, name = "test_cat"),
# id = pet_id,
# tags = list(
# Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")
# ),
# status = "available"
#)
#
# print("==========")
pig <- Pig$new()
basque_pig <- pig$fromJSON(basque_pig_json)
# #print(basque_pig$actual_instance$color)
# #expect_equal(basque_pig$actual_type, "BasquePig")
# pig$fromJSON(danish_pig_json)
# #pig$fromJSON(wrong_json)
# pig$toJSON()
##jsonlite::minify(pet$toJSONString())
##cat(pet$toJSONString())
#toString(pet$toString())
#
# #d <- DanishPig$new()
# #dp <- d$validateJSON(danish_pig_json)
##json <-
##'[
## {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"},
## {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"},
## {},
## {"Name" : "Bowser", "Occupation" : "Koopa"}
##]'
##
##
###Pet$public_methods
###Pet$public_methods$fromJSON(json)
###Pet$public_methods$toJson()
###Pet$public_methods$validateJSON(json2)
###Pet$public_methods$validateJson(json)
###Pet$my_static_method <- function(x) { x + 2}
###Pet$public_methods$my_static_method(1)
##
# basque_pig_json <-
# '{"className2": "BasquePig", "color": "red"}'
##
## danish_pig_json <-
## '{"className2": "DanishPig", "size": 7}'
##
## wrong_json <-
## '[
## {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"},
## {},
## {"Name" : "Ada", "Occupation" : "Engineer"}
## ]'
##
## print("==========")
# pig <- Pig$new()
# basque_pig <- pig$fromJSON(basque_pig_json)
## #print(basque_pig$actual_instance$color)
## #expect_equal(basque_pig$actual_type, "BasquePig")
## pig$fromJSON(danish_pig_json)
## #pig$fromJSON(wrong_json)
## pig$toJSON()
##
## #d <- DanishPig$new()
## #dp <- d$validateJSON(danish_pig_json)
##
##
#
## test nested oneOf
#nested_oneof <- NestedOneOf$new()
#nested_oneof$nested_pig <- pig
#nested_oneof$size <- 15
#
#cat(nested_oneof$toJSONString())
#
# test nested oneOf
nested_oneof <- NestedOneOf$new()
nested_oneof$nested_pig <- pig
nested_oneof$size <- 15
cat(nested_oneof$toJSONString())

View File

@@ -92,6 +92,13 @@ test_that("GetPetById", {
)
})
test_that("GetPetByIdStreaming", {
result <- tryCatch(
pet_api$GetPetByIdStreaming(pet_id, stream_callback = function(x) { print(x) }),
ApiException = function(ex) ex
)
})
#test_that("test GetPetById exception", {
# # test exception
# result <- tryCatch(petApi$GetPetById(98765), # petId not exist