-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathods-import-httr2.R
211 lines (183 loc) · 5.63 KB
/
ods-import-httr2.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
if(!require("pacman")){
install.packages("pacman")
} else {
library("pacman")
}
#remove.packages("pacman", lib = "/usr/lib/R/site-library")
packages <- c("httr2",
"jsonlite",
"tidyverse",
"glue",
"lubridate")
p_load(char = packages)
# 1.0 Utility Functions ----
# Return a tibble of fields and their data types
get_fields_fnc <- function(dataset, ...) {
#include the dots to pass apikey for restricted datasets
base_url <-
"https://opendata.bristol.gov.uk/api/v2/catalog/datasets/"
fields_1_tbl <- request(base_url) %>%
req_url_path_append(dataset) %>%
req_url_query(...) %>%
req_perform() %>%
resp_body_string() %>%
fromJSON() %>%
pluck("dataset", "fields")
if("timeserie_precision" %in% colnames(fields_1_tbl$annotations)){
fields_tbl <- fields_1_tbl %>%
mutate(precision = .$annotations$timeserie_precision) %>%
mutate(type = case_when( # account for dates where precision is not day
precision == "year" ~ "int",
precision == "month" ~ "text",
precision == "day" ~ "date",
TRUE ~ type
)) %>%
select(-annotations, -precision) %>%
as_tibble()
} else {
fields_tbl <- fields_1_tbl %>%
select(-annotations) %>%
as_tibble()
}
data_type_tbl <- tribble(
~ ODS_type,
~ R_type,
~ abb,
"text",
"character",
"c",
"int",
"integer",
"i",
"date",
"date",
"D",
"datetime",
"datetime",
"T",
"double",
"double",
"d",
"geo_point_2d",
"character",
"c",
"geo_shape",
"character",
"c",
"file",
"character",
"c"
)
fields_tbl %>%
left_join(data_type_tbl, by = c("type" = "ODS_type")) %>%
return()
}
# return an ordered tbl of the selected fields with the abbreviated col_types
get_col_types_fnc <- function(select_str, allcols_tbl) {
if (select_str == "*" || is.null(select_str)) {
col_tbl <- allcols_tbl
} else if (str_detect(select_str, ", ")) {
col_tbl <-
filter(allcols_tbl, name %in% as_vector(str_split(select_str, pattern = ", ")))
} else {
col_tbl <- filter(allcols_tbl, name %in% select_str)
}
# do some re ordering if a selection of fields are queried so that col_types matche
# field order
if (select_str == "*" || is.null(select_str)) {
# (str_detect(select_str, ", ")) {
select_ordered_tbl <- col_tbl
} else if (str_detect(select_str, ", ")) {
select_ordered_tbl <-
enframe(unlist(str_split(select_str, pattern = ", "))) %>%
inner_join(col_tbl, by = c("value" = "name"))
}
return(select_ordered_tbl)
}
# Date Helper ----
datehelper_fnc <- function(dateon, dateoff) {
# make a range string from two dates
dates_chr <- c("dateon" = dateon, "dateoff" = dateoff)
dates_vec <-
parse_date_time2(dates_chr,
orders = c("Ymd",
"dmY",
"YmdHMS",
"dmYHMS",
"YmdHM",
"dmYHM",
"Y",
"mY"))
# stopifnot(!any(is.na(dates_vec)),
# dates_vec[2] > dates_vec[1])
tp <- strftime(dates_vec, format = "%Y-%m-%dT%H:%M:%S")
where_str_date_portion <- glue(" IN ['{tp[1]}' TO '{tp[2]}']")
return(where_str_date_portion)
}
# 2.0 Wrapper Function ----
# select endpoint = "records" and format = "json" for grouped queries
# select endpoint = "exports" and format = "csv" for raw records
import_ods <- function(dataset,
endpoint = "exports",
group_by = NULL,
date_col = NULL,
dateon = NULL,
dateoff = NULL,
format = "csv",
select = NULL,
where = NULL,
...) {
base_url <-
"https://opendata.bristol.gov.uk/api/v2/catalog/datasets/"
if (endpoint == "records") {
format <- ""
}
allcols_tbl <- get_fields_fnc(dataset, ...)
column_tbl <- get_col_types_fnc(select_str = select,
allcols_tbl)
# remake the correctly ordered select query string
select_str_ordered <- paste0(column_tbl[["value"]],
collapse = ", ")
# make the shortcut string for col types
col_type <- paste0(column_tbl[["abb"]], collapse = "")
# browser()
# Make the where_str: if date_col and dates present construct a date range string
# and add to the other terms for the filter given in where_str
if (is.character(date_col) &
is.character(dateon) & is.character(dateoff)) {
dateportion <- datehelper_fnc(dateon, dateoff)
if (where == "" || is.null(where)) {
where <- glue("{date_col}{dateportion}")
} else {
where <- glue("({where}) AND {date_col}{dateportion}")
}
} else {
if (where == "" || is.null(where)) {
#if there's no date filter and no other filter limit query to 1000
limit <- 1000L
}
}
params <- list(select = select,
where = where,
group_by = group_by,
...)
resp <- request(base_url) %>%
req_url_path_append(dataset) %>%
req_url_path_append(endpoint) %>%
req_url_path_append(format) %>%
req_url_query(!!!params) %>%
req_user_agent("steve c") %>%
req_perform()
if (format == "csv") {
out <- resp %>%
resp_body_raw() %>%
read_delim(delim = ";",
col_types = col_type)
} else {
out <- resp %>%
resp_body_json() %>%
pluck("records") %>%
map_df(~ pluck(.x, "record", "fields"))
}
return(out)
}