R API Server / jug 사용하기 How to use R as a simple API server

필요성 Why you need this?


  • R로 서버를 구축하여 통계 데이터를 뿌려줄 때 If you want to distribute data or results from R
  • Shiny를 사용하는 대신 간단히 결과만 알려주고자 할 때 If you hate Shiny servers
  • API 서버란? Application Programming Interface의 약자. 웹으로 각종 함수를 실행하여 결과를 받아볼 수 있도록 한 서버 What is an API server? It refers to a simple server program for executing functions from remote sites.

패키지 설치 Install package

> install.packages("jug")

GET

>library(jug)

기본적으로 chain rule이 적용된다. The package, jug, is applied by Chain Rule as does in {dplyr}.

> jug()%>%
  get(path='/',
      function(req,res,err){
        "Hello World!!"
      })%>%
  get(path='/name',
      function(req,res,err){
        "My name is Taekyung!"
      })%>%
  serve_it()

결과는 다음과 같다. The result is followed.
http://127.0.0.1:8080

 http://127.0.0.1:8080/name


모듈 프로그래밍을 하려면 collector()와 include()를 사용한다. If you need a modular program, consider collector() and include().

> collected_middle_ware=collector()%>%
  get("/",function(req,res,err){
    "Hello World!!!"
  })
> res=jug()%>%
  include(collected_middle_ware)%>%
  serve_it()

함수 사용하기 Function

함수를 사용해서 간단하게 서비스를 구축할 수 있다. 이때 decorate()를 사용한다. You can also use own functions for simple service. Consider decorate() in this case.

> say_hello<-function(name){paste("hello",name,"!")}
# http://127.0.0.1:8080?name=taekyung
> jug() %>%
  get("/", decorate(say_hello)) %>%
  serve_it()

결과는 다음과 같다. The result is followed.

JSON Line 사용하기 Use JSON Line

결과 데이터를 JSON Line 형태로 뿌려주려면 data.frame 객체나 tibble 객체를 사용한다. If you need to distribute JSON Line data, use data.frame objects or tibble objects.

예제는 다음과 같다. An example is followed.

> library(dplyr)
> jug()%>%
  get(path='/',function(req,res,err){
    output=data_frame(x=c(10,100),y=c(20,200))
    res$json(output)
  })%>%
  serve_it()

Plotting하기 How to plot?

이미지를 Plotting하기 위해서는 res$plot()을 사용한다. Use res$plot for plotting. 이때 base64=FALSE로 하여 브라우저가 바로 데이터를 읽을 수 있도록 할 수 있다. Set base64=FALSES to read image data directly from a web browser.
우선 test.html을 작성하자. Let's write "test.html" file.


R로 API 서버 코드를 작성한다. Let's code an R API server.

>jug()%>%
  get("/",function(req,res,err){
    res$plot(with(mtcars,plot(gear,mpg)),base64=FALSE)
  })%>%
  serve_it()

이제 test.html을 브라우저로 실행시켜면 다음과 같다. Now test it.



사례 mtcars Case mtcars

간단한 사례를 살펴보자. A simple case

> mpg_model<-
  lm(mpg~gear+hp, data=mtcars)
> predict_mpg <- function(gear, hp){
  predict(mpg_model,
          newdata = data.frame(gear=as.numeric(gear),
                               hp=as.numeric(hp)))[[1]]
}
> jug() %>%
  get("/predict-mpg", decorate(predict_mpg)) %>%
  simple_error_handler_json() %>%
  serve_it()

결과는 다음과 같다. Result.
http://127.0.0.1:8080/predict-mpg?gear=4&hp=80

Host, port 옵션 How to set host and port?

서비스 주소와 포트를 변경하려면 serve_it()으로 옵션을 변경한다. 예를 들어 주소가 127.101.101.1이고 포트가 9000이라면, If address is 127.101.101.1 and port is 900,

serve_it(host="127.101.101.1",port=9000)




댓글

이 블로그의 인기 게시물

R에서 csv 파일 읽는 법

xlwings tutorial - 데이터 계산하여 붙여 넣기