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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! # Endpoints Module
//!
//! This module defines the various endpoints available in the Library of Congress API.
//! It includes enums and methods for constructing URLs based on different API endpoints
//! and their respective parameters.
use std::error::Error;
use serde::{Serialize, Deserialize};
use crate::{param_models::*, format_models::*};
/// Represents the various endpoints available in the Library of Congress API.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Endpoints {
/// The `/search/` endpoint for general searches across the LOC website.
Search(SearchParams),
/// The `/collections/` endpoint to retrieve all digital collections.
Collections(CommonParams),
/// The `/collections/{name_of_collection}/` endpoint for a specific collection.
Collection {
name: String,
params: CommonParams,
},
/// The `/{format}/` endpoint to retrieve items of a specific format.
///
/// The format can be one of the following:
/// - Audio
/// - Books
/// - Film and Videos
/// - Legislation
/// - Manuscripts
/// - Maps
/// - Newspapers
/// - Photos
/// - Notated Music
/// - Web Archives
///
/// # Fields
/// - `format`: The specific format type.
/// - `params`: Parameters specific to the format endpoint, such as formatting and
/// attribute selection.
Format {
format: MediaType,
params: CommonParams,
},
/// The `/item/{item_id}/` endpoint to retrieve detailed information about a specific item.
///
/// # Fields
///
/// - `item_id`: The unique identifier of the item. This should be the part of the URL that identifies the item.
/// - `params`: Parameters specific to the item endpoint, such as formatting and attribute selection.
Item {
item_id: String,
params: ItemParams,
},
/// The `/resource/{resource_id}/` endpoint to retrieve information about a specific resource.
Resource {
resource_id: String,
params: ResourceParams,
},
}
fn to_url_helper(common: &CommonParams) -> String {
let format = common.format.unwrap_or(Format::Json).slug();
let attributes = match common.attributes {
Some(ref attrs) => attrs.to_query_param(),
None => "".to_string(),
};
let query = match common.query {
Some(ref q) => format!("&q={}", q),
None => "".to_string(),
};
let filter = match common.filter {
Some(ref f) => format!("&fa={}", f.to_query_param()),
None => "".to_string(),
};
let per_page = match common.per_page {
Some(c) => format!("&c={}", c),
None => "".to_string(),
};
let page = match common.page {
Some(p) => format!("&sp={}", p),
None => "1".to_string(),
};
let sort = match common.sort {
Some(s) => format!("&sb={}", s.slug()),
None => "".to_string(),
};
format!(
"?fo={}&{}{}{}{}{}{}",
format, attributes, query, filter, per_page, page, sort
)
}
impl Endpoints {
/// Constructs the full URL for the API request based on the endpoint and its parameters.
///
/// # Examples
///
/// ```rust
/// use loc_api::{endpoints::*, param_models::*, format_models::*,
/// attribute_models::*};
///
/// let common_params = CommonParams {
/// format: Some(Format::Json),
/// attributes: Some(AttributesSelect {
/// include: vec!["pagination".to_string(), "results".to_string()],
/// exclude: vec![],
/// }),
/// query: Some("dog".to_string()),
/// filter: Some(FacetReq {
/// filters: vec![Facet::Subject { value: "animals".to_string() }],
/// }),
/// per_page: Some(25),
/// page: Some(1),
/// sort: Some(SortField::TitleS),
/// };
///
/// let format_params = CommonParams {
/// format: Some(Format::Json),
/// ..common_params.clone()
/// };
///
/// let format_endpoint = Endpoints::Format {
/// format: MediaType::FilmAndVideos,
/// params: format_params,
/// };
///
/// let url = format_endpoint.to_url().unwrap();
/// assert_eq!(url, "https://www.loc.gov/film-and-videos/?fo=json&at=pagination,results&q=dog&fa=subject:animals&c=25&sp=1&sb=title_s");
/// ```
pub fn to_url(&self) -> Result<String, Box<dyn Error>> {
let base_url = "https://www.loc.gov";
match self {
Endpoints::Search(params) => {
let mut url = format!("{}/search/", base_url);
let query_string = to_url_helper(¶ms.common);
if !query_string.is_empty() {
url.push_str(&query_string);
} else {
return Err("No query parameters provided".to_string().into());
}
Ok(url)
},
Endpoints::Collections(params) => {
// collection param must be in "kebab-case"
let mut url = format!("{}/collections/", base_url);
let query_string = to_url_helper(¶ms);
if !query_string.is_empty() {
url.push_str(&query_string.replace(" ", "-"));
} else {
return Err("No query parameters provided".to_string().into());
}
Ok(url)
},
Endpoints::Collection { name, params } => {
let mut url = format!("{}/collections/{}/", base_url, name);
let query_string = to_url_helper(¶ms);
if !query_string.is_empty() {
url.push_str(&query_string.replace(" ", "-"));
} else {
return Err("No query parameters provided".to_string().into());
}
Ok(url)
},
Endpoints::Format { format, params } => {
let format_slug = format.slug();
let mut url = format!("{}/{}/", base_url, format_slug);
let query_string = to_url_helper(¶ms);
if !query_string.is_empty() {
url.push_str(&query_string);
} else {
return Err("No query parameters provided".to_string().into());
}
Ok(url)
},
Endpoints::Item { item_id, params } => {
let mut url = format!("{}/item/{}/", base_url, item_id);
let format = params.format.unwrap_or(Format::Json).slug();
let attributes = match params.attributes {
Some(ref attrs) => {
let mut parts = Vec::new();
if let Some(item_attrs) = attrs.item {
if item_attrs {
parts.push("at=item".to_string());
}
}
if let Some(resource_attrs) = attrs.resources {
if resource_attrs {
parts.push("at=resources".to_string());
}
}
if let Some(cite_this) = attrs.cite_this {
if cite_this {
parts.push("at=cite_this".to_string());
}
}
parts.join("&")
}
None => "".to_string(),
};
let query_string = format!("?fo={}&{}", format, attributes);
if !query_string.is_empty() {
url.push_str(&query_string);
}
Ok(url)
},
Endpoints::Resource { resource_id, params } => {
let mut url = format!("{}/resource/{}/", base_url, resource_id);
let format = params.format.unwrap_or(Format::Json).slug();
let attributes = match params.attributes {
Some(ref attrs) => {
let mut parts = Vec::new();
if let Some(resource_attrs) = attrs.resource {
if resource_attrs {
parts.push("at=resource".to_string());
}
}
if let Some(page_attrs) = attrs.page {
if page_attrs {
parts.push("at=page".to_string());
}
}
if let Some(segment_attrs) = attrs.segments {
if segment_attrs {
parts.push("at=segments".to_string());
}
}
if let Some(cite_this) = attrs.cite_this {
if cite_this {
parts.push("at=cite_this".to_string());
}
}
if let Some(resources) = attrs.resources {
if resources {
parts.push("at=resources".to_string());
}
}
parts.join("&")
}
None => "".to_string(),
};
let query_string = format!("?fo={}&{}", format, attributes);
if !query_string.is_empty() {
url.push_str(&query_string);
}
Ok(url)
},
}
}
}