APIs and Web Scraping in R

📘 Introduction

APIs (Application Programming Interfaces) and Web Scraping are two common techniques for collecting data from the internet. APIs provide structured and authorized access to data, while web scraping extracts information directly from web pages by parsing their HTML content. R offers powerful packages for both approaches, enabling developers and data analysts to build automated data collection workflows.

Information

Whenever an official API is available, it should generally be preferred over web scraping because APIs provide structured, reliable, and legally supported access to data.

đŸŽ¯ Why Learn APIs and Web Scraping?

  • Collect real-time data from online services.
  • Automate data collection processes.
  • Access public datasets and online resources.
  • Build data-driven dashboards and applications.
  • Support research, analytics, and machine learning projects.

📚 APIs vs Web Scraping

FeatureAPIWeb Scraping
Data FormatStructured (JSON, XML).HTML pages.
ReliabilityHigh.Depends on website structure.
SpeedUsually faster.Often slower.
AuthenticationMay require API keys.Usually not required.
RecommendedYes, when available.When no suitable API exists.

đŸ“Ļ Installing Required Packages

Install Packages

install.packages("httr")
install.packages("jsonlite")
install.packages("rvest")
install.packages("xml2")

library(httr)
library(jsonlite)
library(rvest)
library(xml2)

🌐 API Workflow

Find API
Send Request
Receive Response
Parse JSON/XML
Analyze Data

📡 Sending an HTTP GET Request

The GET() function retrieves data from a web API.

GET Request

library(httr)

response <- GET(
  "https://api.example.com/users"
)

status_code(
  response
)

📄 Reading JSON Data

Many APIs return data in JSON format, which can be converted into R objects.

Parse JSON

library(jsonlite)

response <- GET(
  "https://api.example.com/users"
)

data <- fromJSON(

  content(
    response,
    "text"
  )

)

head(data)

🔑 Using API Keys

Some APIs require authentication using an API key.

Authenticated API Request

response <- GET(

  "https://api.example.com/data",

  add_headers(

    Authorization =

      "Bearer YOUR_API_KEY"

  )

)

📤 Sending POST Requests

POST requests send data to a server, often when creating new resources.

POST Request

response <- POST(

  "https://api.example.com/users",

  body = list(

    name = "Alice",

    age = 25

  ),

  encode = "json"

)

📊 Working with API Responses

Inspect Response

status_code(
  response
)

headers(
  response
)

content(
  response
)

📋 Common HTTP Methods

MethodPurpose
GETRetrieve data.
POSTCreate new data.
PUTReplace existing data.
PATCHUpdate part of existing data.
DELETERemove data.

🕸 Introduction to Web Scraping

Web scraping extracts information directly from HTML pages using CSS selectors or XPath expressions.

Read a Web Page

library(rvest)

page <- read_html(

  "https://example.com"

)

📖 Extracting Page Titles

Extract Title

page %>%

  html_element(

    "title"

  ) %>%

  html_text()

📑 Extracting Text

Extract Paragraphs

page %>%

  html_elements(

    "p"

  ) %>%

  html_text()

🔗 Extracting Links

Extract Hyperlinks

page %>%

  html_elements(

    "a"

  ) %>%

  html_attr(

    "href"

  )

📊 Extracting Tables

HTML tables can be converted directly into R data frames.

Read HTML Tables

tables <- page %>%

  html_table()

tables[[1]]

đŸŽ¯ Using CSS Selectors

CSS selectors identify specific HTML elements for extraction.

CSS Selector Example

page %>%

  html_elements(

    ".article-title"

  ) %>%

  html_text()

📍 Using XPath

XPath provides another way to locate HTML elements.

XPath Example

page %>%

  html_elements(

    xpath =

      "//h2"

  ) %>%

  html_text()

💾 Saving Scraped Data

Save to CSV

titles <- page %>%

  html_elements(

    "h2"

  ) %>%

  html_text()

write.csv(

  titles,

  "titles.csv",

  row.names = FALSE

)

🌍 Real-World Example

A financial analyst collects daily stock information using a public financial API. When historical news headlines are unavailable through an API, the analyst scrapes article titles from publicly accessible news pages, respecting the website's terms of service and usage policies.

News Headline Extraction

library(rvest)

page <- read_html(

  "https://example.com/news"

)

headlines <- page %>%

  html_elements(

    "h2"

  ) %>%

  html_text()

print(
  headlines
)

🔄 Data Collection Workflow

Identify Data Source
Choose API or Web Scraping
Retrieve Data
Parse Response
Clean Data
Analyze Data
Store Results

📋 Common Functions

FunctionPurpose
GET()Sends an HTTP GET request.
POST()Sends an HTTP POST request.
fromJSON()Parses JSON data.
read_html()Reads an HTML page.
html_element()Selects a single HTML element.
html_elements()Selects multiple HTML elements.
html_text()Extracts text content.
html_table()Extracts HTML tables.
html_attr()Extracts HTML attributes.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Ignoring API documentationRequests may fail due to incorrect parameters.Read the API documentation carefully before making requests.
Hardcoding API keysCredentials may be exposed.Store API keys securely using environment variables or configuration files.
Scraping websites too aggressivelyMay overload servers or violate usage policies.Respect rate limits, robots.txt guidance where appropriate, and the website's terms of service.
Assuming HTML structure never changesScrapers can stop working when websites are updated.Write robust selectors and periodically maintain scraping code.

💡 Best Practices

  • Use official APIs whenever they are available.
  • Read API documentation before integrating with a service.
  • Handle HTTP errors and unexpected responses gracefully.
  • Keep API credentials secure and never expose them publicly.
  • Respect website terms of service and request rate limits when scraping.
  • Clean and validate collected data before analysis.
  • Cache responses when appropriate to reduce unnecessary requests.

Best Practice

APIs provide the most reliable and maintainable way to collect online data, while web scraping is useful when structured APIs are unavailable. By combining secure API usage, responsible scraping practices, robust error handling, and efficient data processing, you can build dependable data collection pipelines in R.

📝 Summary

APIs and web scraping enable R to collect data from online sources for analysis and automation. In this chapter, you learned how to send HTTP requests using the httr package, parse JSON responses with jsonlite, authenticate using API keys, perform GET and POST requests, and inspect API responses. You also explored web scraping using rvest, including reading HTML pages, extracting text, links, tables, and attributes with CSS selectors and XPath expressions. Mastering these techniques allows you to build automated workflows that gather, process, and analyze data from the web efficiently and responsibly.

>>"The web is one of the richest sources of data—APIs provide structured access, while responsible web scraping unlocks information when APIs are unavailable."