-
Notifications
You must be signed in to change notification settings - Fork 23
/
2-news-shiny.R
57 lines (47 loc) · 1.21 KB
/
2-news-shiny.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
library(shiny)
library(httr2)
get_news_articles <- function(search_term, num_results = 10) {
req <- request("https://newsapi.org/v2/everything") |>
req_url_query(
q = search_term,
from = Sys.Date() - 1,
pageSize = num_results,
apiKey = Sys.getenv("NEWS_API_KEY")
)
resp <- req_perform(req)
resp_body_json(resp)
}
ui <- fluidPage(
titlePanel("News Article Search"),
sidebarLayout(
sidebarPanel(
textInput("search_term", "Enter a search term:"),
actionButton("search", "Search")
),
mainPanel(
uiOutput("articles")
)
)
)
server <- function(input, output, session) {
articles <- eventReactive(input$search, {
get_news_articles(input$search_term, num_results = 10)
})
output$articles <- renderUI({
req(articles())
article_list <- articles()$articles
if(length(article_list) == 0) {
return(h3("No articles found."))
}
lapply(article_list, function(article) {
div(
h3(a(article$title, href = article$url)),
p(strong("Source:"), article$source$name),
p(strong("Published at:"), article$publishedAt),
p(article$description),
hr()
)
})
})
}
shinyApp(ui, server)