Your Hero Moment! - Hitting your first API with R

POSTED IN: Building Bridges from R to IBM Watson

Introduction to “R” and APIs for Non-Developers - Hero Moments with R and IBM Watson Services:

Document Purpose  

Most people don't code. Most people don't know how to “hit” an API.  But as the technology evolves – having a basic understanding of APIs and microservices is quickly becoming a technology table stake – much like Microsoft Excel was in the late 1980s; and Web in mid 1990’s.

The purpose of this document is:
1.    to help you execute your first bit of code and access an API to do something
2.    to demystify APIs a little
3.    to give you three small “Hero Moments”  
4.    to casually mention to Stan at the water cooler that you ‘did a little coding’ over the weekend

We’ve made this REALLY easy.  If you can sum two columns in Excel, then you are going to be fine. We tested this document on several non-devs and an 8-year old child. If they can do it, so can you!


Primary audience is non-technical teams (Sales, Marketing; HR, Communications) working in the Cloud / API space
Secondary audiences may include kids (STEM Labs) & others curious about code and IBM Watson.

R Programming Language (or “R”)

R is a language and environment for statistical computing and graphics and provides a wide variety of statistical (linear and nonlinear modelling, classical statistical tests, time-series analysis, classification, clustering, and graphical techniques.
•    R Programming Language is Open Source - https://www.r-project.org/about.html
•    R Consortium has 3 Platinum members https://www.r-consortium.org/about/members (IBM)
•    R's popularity has increased substantially in recent years.
•    RStudio is an free and open-source integrated development environment (IDE) for R.  In a nutshell, that means it sits on top of R, and makes things (like package installs) lots easier.
•    R is highly extensible through the use of user-submitted packages (like WatsonR)

Three Parts

We’ve broken up this tutorial into three bite sized parts – the first two should take about 20 minutes. The third one 30-60 minutes.  They can be done in one sitting, or done over a few days.
  PART 1 - INSTALL TOOLS - Install R and R Studio
  PART 2 - API CREDENTIALS - Create API services in IBM Bluemix, and save the keys/credentials  
  PART 3 - CODE AND CALL APIS – Copy and paste code; follow a few steps; and run code/hit API

Part 1 – Install Tools

This part is easy – it involves downloading software, installing it, and validating it.   It has 3 pieces:
i.    R Programming Language (the core of the programming language)
ii.    R Studio (Integrated Development Environment – IDE) – editor, tools, ‘easy buttons’
iii.    Packages for R - Packages are pre-built collections of R functions, data, and code


R Programming Language

STEP 1.1:    Go to https://cloud.r-project.org/ Click on Download R for Mac (or Windows)

STEP 1.2:    Click on the latest .PKG.   Download, Open and Install

Trouble? Just go to YouTube and search for “how to install r” – lots of good videos

STEP 1.3:    Launch R by clicking icon.  Verify some simple math

type in “2+2”;  or if you want to get fancy “x=2” then “y=3” and then “print(x+y)”

One down, two to go.


R Studio

STEP 1.4:    Go to https://www.rstudio.com/products/rstudio/ - click on Desktop

STEP 1.5:    Click on INSTALLERS for the RStudio (Mac or Windows)

STEP 1.6:    Follow instructions, Install and test

Type in 2+2 in bottom left corner.  This confirms both RStudio AND R, are installed and working

Two down, one to go.

Packages for R

Packages are pre-built collections of R functions, data, and code.  They extend the capabilities of R to do more things. Like extra powers.   For example,

STEP 1.7:    Click on Bottom Right Quadrant “PACKAGES” tab: Then INSTALL button


STEP 1.8:    Populate the Packages with the names below, and press install. Wait for a bit.
Paste packages in this box (one by one, or comma separated)
RCurl, httr, (the others are optional here)

you can also type > install.packages("RCurl") in the bottom left panel


STEP 1.9:    Test Packages installed by
Copy and paste these two lines to the bottom left console – test R can talk to the Web
•    library(RCurl)
•    getURL("https://en.wikipedia.org/wiki/Wayne_Gretzky")

you should see a bunch of responses referencing hockey lore - a sign that R is communicating with Web.



Part 2 – API Credentials

Create IBM Watson Developer Cloud Service – on Bluemix

STEP 2.1:    Sign Up for IBM Bluemix  https://console.ng.bluemix.net/


STEP 2.2:    Fill in in information and verify account


STEP 2.3:    Login to Bluemix.  Click on DASHBOARD. And then SERVICES & APIs Tile


STEP 2.4:    Click on ALCHEMYAPI Tile


STEP 2.5:    Press the CREATE Button to Create your AlchemyAPI Service / API Endpoint
You can leave the App Unbound and Name it whatever you like


STEP 2.6:    Wait 10 Seconds.  Click on SERVICE CREDENTIALS – then copy API KEY
Take note of the URL and the APIKEY – this is your own key for your own service. COPY for Later


Part 3 – Code & Call APIs

Test Connection
STEP 3.1:     Execute Three lines of code
You have the option to paste them in the console bottom-left (and press enter) – OR
You can create ‘New-File’ ; paste the code top-left; and then Command/Control + Enter



You are looking for STATUS 200 and STATUS OK Message in the response

Run Your Code


STEP 3.2:    Paste code to Top Left Pane; execute each line with Command/Control + Enter

alchemy_url = "http://gateway-a.watsonplatform.net/calls/text/"
api_feature = "TextGetCombinedData"
api_key = "12345-YOUR-KEY-HERE-6789"
output_mode = "json"
TEXT = "I am happy when I eat strawberry ice cream in Vancouver in my Ford Truck"
TEXT = URLencode(TEXT)
query = paste(alchemy_url,api_feature,"?extract=keyword,doc-sentiment,entity,taxonomy,concept&apikey=",api_key,"&text=",TEXT,"&outputMode=",output_mode, sep="")
response = POST(query)

here’s what it looks like – again STATUS: 200 is a good sign!


when you run the last line, you should get the contents of the API call

STEP 3.3:    PLAY!   Change the TEXT (and re-run the line) – See the results change



What the API services has done is extracted the keywords, entities and sentiment of this unstructured data - and made it structured - for analysis.



Watson Developer Cloud – Surfacing Signals from Unstructured Data

Watson Developer Cloud (WDC) services generally deliver value in these categories:

  1. Data Enrichment, Augmentation & Tagging (enriching & organizing unstructured data )
  2. Sensemaking, Interpretation, and Understanding (comprehending unstructured data)
  3. Interact, Respond and Converse (engaging and interacting with humans)
  4. Translation (translating spoken or typed English intents: to French or HVAC or code)
  5. Visual Recognition and Image Analysis (seeing & interpreting visual data)



Further Reading

  • IBM Blog - Services, microservices, APIs, what granularity, when and which ones.
  • IBM Blog – APIs vs Services – What is the difference
  • IBM Article - Microservices, SOA, and APIs: Friends or enemies?



Unpacking the code

library(RCurl) #Provides functions to allow one to compose general HTTP requests – talk to web pages

library(httr)  #Tools for working with HTTP (GET(), POST(), and authentication) to talk to REST APIs

alchemy_url = "http://gateway-a.watsonplatform.net/calls/text/" #API Endpoint

api_feature = "TextGetCombinedData"  #Tells API which features we want ‘turned on’

api_key = "12345-YOUR-KEY-HERE-6789" #API and authentication (your individual API key)

output_mode = "json" #Format of output to be returned (XML is option too)

TEXT = "I am happy when I eat strawberry ice cream in Vancouver in my Ford Truck" #text to analyze

TEXT = URLencode(TEXT) # this puts%20between%20each%20word so computer can read it

query = paste(alchemy_url,api_feature,"?extract=keyword,doc-sentiment,entity,taxonomy,concept&apikey=",api_key,"&text=",TEXT,"&outputMode=",output_mode, sep="")  # this smooshes the pieces all together

query # this prints the smoothed query for a look (not required, doesn't do anything, just for a peek)

response = POST(query)  # HTTR library function POSTS the query to API; and captures ‘response’

response # prints response header – so we can look for STATUS 200

content(response)  # pulls the CONTENS of the response out


API Documentation & Demo




Keywords - Dogfood , Dogfooding


Interested in more content by this author?

About the Author

Ryan Anderson

Ryan Anderson

Hi! I like to play with data, analytics and hack around with robots and gadgets in my garage. Lately I've been learning about machine learning.

About this blog

This is an informal blog that explores tools, code and tricks that group members have developed to engage IBM Watson cognitive computing services - from the R Programming Language. Packages include RCURL to access Watson APIs - for services that include Natural Language Classifier and Speech to Text. THIS IS MY PERSONAL BLOG - it does not represent the views of my employer. Code is presented as 'use at your own risk' (it has lots of bugs)

Created: September 13, 2015


Up Next