Skip to main content

estat_api/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4pub mod catalog;
5pub mod dataset;
6mod de;
7mod error;
8mod params;
9pub mod response;
10
11pub use catalog::DataCatalog;
12pub use dataset::{DatasetList, PostDataset, RefDataset};
13pub use error::EstatError;
14pub use params::{
15    CollectArea, DataCatalogParams, DataType, DatasetParams, DatasetsParams, Dimension,
16    MetaInfoParams, PostDatasetParams, ReplaceSpChar, SearchKind, StatsDataParams,
17    StatsDatasParams, StatsDatasRequest, StatsListParams,
18};
19pub use response::{
20    ApiResult, Class, ClassInf, ClassObj, DataInf, DataListInf, DataValue, MetaInfo, ResultInf,
21    StatisticalData, StatisticalDataList, StatsData, StatsDatas, StatsList, TableInf,
22};
23
24/// Re-export of `reqwest`, for building a client to pass to
25/// [`EstatApi::with_client`] without adding the dependency yourself.
26pub use reqwest;
27
28use reqwest::Url;
29use serde::Deserialize;
30use serde::de::DeserializeOwned;
31use serde_json::Value;
32use std::fmt::{Debug, Formatter};
33use std::time::Duration;
34
35const DEFAULT_BASE_URL: &str = "https://api.e-stat.go.jp/rest/3.0/app/json";
36// Some catalog searches take more than a minute on the e-Stat side
37const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
38
39/// Environment variable read by [`EstatApi::from_env`].
40pub const APP_ID_ENV: &str = "ESTAT_APP_ID";
41
42/// Language of names and messages in responses (`lang`).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[non_exhaustive]
45pub enum Lang {
46    /// `J`, the default.
47    Japanese,
48    /// `E`. Only some tables have English names.
49    English,
50}
51
52impl Lang {
53    /// Parameter value, `J` or `E`.
54    pub fn code(&self) -> &'static str {
55        match self {
56            Lang::Japanese => "J",
57            Lang::English => "E",
58        }
59    }
60}
61
62/// Client for the e-Stat API v3.0 (JSON).
63///
64/// The application ID is issued after registering on e-Stat and is sent as
65/// the `appId` query parameter.
66///
67/// # Example
68///
69/// ```no_run
70/// use estat_api::{Dimension, EstatApi, StatsDataParams, StatsListParams};
71///
72/// # async fn run() -> Result<(), estat_api::EstatError> {
73/// let api = EstatApi::from_env()?;
74///
75/// let list = api.stats_list(&StatsListParams::new().search_word("人口推計").limit(5)).await?;
76/// for table in &list.datalist_inf.table_inf {
77///     println!("{} {:?}", table.id, table.title.as_ref().map(|t| &t.name));
78/// }
79///
80/// let data = api
81///     .stats_data_all(&StatsDataParams::table("0003448237").code(Dimension::Area, "13000"))
82///     .await?;
83/// for value in data.values() {
84///     println!("{:?} {}", data.label(value, Dimension::Time), value.value);
85/// }
86/// # Ok(())
87/// # }
88/// ```
89#[derive(Clone)]
90pub struct EstatApi {
91    app_id: String,
92    base_url: String,
93    client: reqwest::Client,
94    timeout: Option<Duration>,
95    lang: Option<Lang>,
96}
97
98impl Debug for EstatApi {
99    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
100        f.debug_struct("EstatApi")
101            .field("app_id", &"<redacted>")
102            .field("base_url", &self.base_url)
103            .field("timeout", &self.timeout)
104            .field("lang", &self.lang)
105            .finish_non_exhaustive()
106    }
107}
108
109impl EstatApi {
110    /// Client with the given application ID. Requests time out after 5 minutes.
111    pub fn with_app_id<T: Into<String>>(app_id: T) -> Self {
112        EstatApi {
113            app_id: app_id.into(),
114            base_url: DEFAULT_BASE_URL.to_string(),
115            client: reqwest::Client::new(),
116            timeout: Some(DEFAULT_TIMEOUT),
117            lang: None,
118        }
119    }
120
121    /// Client with the application ID in the `ESTAT_APP_ID` environment variable.
122    ///
123    /// # Errors
124    ///
125    /// [`EstatError::InvalidArgument`] when the variable is not set or empty.
126    pub fn from_env() -> Result<Self, EstatError> {
127        Self::from_app_id(std::env::var(APP_ID_ENV).ok())
128    }
129
130    fn from_app_id(app_id: Option<String>) -> Result<Self, EstatError> {
131        app_id
132            .filter(|id| !id.is_empty())
133            .map(Self::with_app_id)
134            .ok_or_else(|| EstatError::InvalidArgument(format!("{APP_ID_ENV} is not set")))
135    }
136
137    /// Uses the given HTTP client, for example one with a proxy. The 5 minute
138    /// default no longer applies, so set a timeout on the client if you want one.
139    pub fn with_client(mut self, client: reqwest::Client) -> Self {
140        self.client = client;
141        self.timeout = None;
142        self
143    }
144
145    /// Timeout for each request, including reading the body.
146    pub fn with_timeout(mut self, timeout: Duration) -> Self {
147        self.timeout = Some(timeout);
148        self
149    }
150
151    /// Language of the responses. Without it e-Stat answers in Japanese.
152    pub fn with_lang(mut self, lang: Lang) -> Self {
153        self.lang = Some(lang);
154        self
155    }
156
157    /// Changes the API base URL (default `https://api.e-stat.go.jp/rest/3.0/app/json`).
158    /// Mainly for tests against a mock server.
159    pub fn with_base_url<T: Into<String>>(mut self, base_url: T) -> Self {
160        self.base_url = base_url.into().trim_end_matches('/').to_string();
161        self
162    }
163
164    /// Searches statistical tables (`getStatsList`, 統計表情報取得).
165    ///
166    /// # Errors
167    ///
168    /// * [`EstatError::Api`] when e-Stat reports an error, such as `100` for
169    ///   a wrong application ID or `102` for an invalid parameter value.
170    /// * [`EstatError::Connection`] on a network failure or timeout,
171    ///   [`EstatError::HttpStatus`] when the server answers with an error page,
172    ///   [`EstatError::JsonParse`] or [`EstatError::UnexpectedResponse`] when
173    ///   the body is not the expected JSON.
174    pub async fn stats_list(&self, params: &StatsListParams) -> Result<StatsList, EstatError> {
175        self.request("getStatsList", "GET_STATS_LIST", params.query())
176            .await
177    }
178
179    /// Dimensions and items of a table (`getMetaInfo`, メタ情報取得).
180    /// Takes a table ID or [`MetaInfoParams`].
181    ///
182    /// # Errors
183    ///
184    /// [`EstatError::Api`] with `300` (see [`EstatError::is_not_found`]) when
185    /// no table has the ID. Otherwise the same as [`stats_list`](Self::stats_list).
186    pub async fn meta_info(
187        &self,
188        params: impl Into<MetaInfoParams>,
189    ) -> Result<MetaInfo, EstatError> {
190        let params = params.into();
191        self.request("getMetaInfo", "GET_META_INFO", params.query())
192            .await
193    }
194
195    /// One page of values of a table or dataset (`getStatsData`, 統計データ取得).
196    ///
197    /// A page holds up to `limit` values (100,000 by default). When there are
198    /// more, [`StatsData::next_key`] is the start of the next page; pass it to
199    /// [`StatsDataParams::start_position`], or use
200    /// [`stats_data_all`](Self::stats_data_all).
201    ///
202    /// # Errors
203    ///
204    /// Same as [`meta_info`](Self::meta_info).
205    pub async fn stats_data(&self, params: &StatsDataParams) -> Result<StatsData, EstatError> {
206        self.request("getStatsData", "GET_STATS_DATA", params.query())
207            .await
208    }
209
210    /// All values, following `NEXT_KEY` until the last page.
211    ///
212    /// The first page is requested with `params` as given; later pages are
213    /// requested without metadata. The result has the table and metadata of
214    /// the first page and the values of all pages, with `NEXT_KEY` cleared.
215    /// Large tables take many requests, so narrow them down with filters.
216    ///
217    /// # Errors
218    ///
219    /// Same as [`stats_data`](Self::stats_data), and
220    /// [`EstatError::UnexpectedResponse`] if `NEXT_KEY` does not move forward.
221    pub async fn stats_data_all(&self, params: &StatsDataParams) -> Result<StatsData, EstatError> {
222        let mut data = self.stats_data(params).await?;
223        let mut next = data.next_key();
224        while let Some(start) = next {
225            let page = self
226                .stats_data(&params.with_start(start).meta(false))
227                .await?;
228            next = page.next_key();
229            if let Some(following) = next.filter(|&n| n <= start) {
230                return Err(EstatError::UnexpectedResponse(format!(
231                    "NEXT_KEY {following} does not move past {start}"
232                )));
233            }
234            let page = page.statistical_data;
235            let merged = &mut data.statistical_data;
236            merged.result_inf.to_number = page.result_inf.to_number;
237            merged.result_inf.next_key = None;
238            for annotation in page.data_inf.annotation {
239                if !merged.data_inf.annotation.contains(&annotation) {
240                    merged.data_inf.annotation.push(annotation);
241                }
242            }
243            merged.data_inf.value.extend(page.data_inf.value);
244        }
245        Ok(data)
246    }
247
248    /// Searches the data catalog: Excel, CSV and PDF files and database
249    /// tables on e-Stat (`getDataCatalog`, データカタログ情報取得).
250    ///
251    /// # Errors
252    ///
253    /// Same as [`stats_list`](Self::stats_list).
254    pub async fn data_catalog(
255        &self,
256        params: &DataCatalogParams,
257    ) -> Result<DataCatalog, EstatError> {
258        self.request("getDataCatalog", "GET_DATA_CATALOG", params.query())
259            .await
260    }
261
262    /// Values of several tables or datasets in one request (`getStatsDatas`,
263    /// 統計データ一括取得). The requests together may return at most 100,000
264    /// values, and there is no paging; use [`stats_data`](Self::stats_data)
265    /// for more.
266    ///
267    /// # Errors
268    ///
269    /// [`EstatError::Api`] with `400` when the requests select too many
270    /// values, or `401` when one of them fails (the message names the
271    /// request and its error). Otherwise the same as [`stats_list`](Self::stats_list).
272    pub async fn stats_datas(&self, params: &StatsDatasParams) -> Result<StatsDatas, EstatError> {
273        let url = endpoint(&self.base_url, "getStatsDatas")?;
274        let request = self.client.post(url).form(&self.pairs(&params.form()));
275        let (status, text) = self.send(request).await?;
276        parse_json(status, &text, "GET_STATS_DATAS")
277    }
278
279    /// Datasets you can use: your own and those others made public
280    /// (`refDataset` without an ID, データセット参照).
281    ///
282    /// # Errors
283    ///
284    /// Same as [`stats_list`](Self::stats_list).
285    pub async fn datasets(&self, params: &DatasetsParams) -> Result<DatasetList, EstatError> {
286        self.request("refDataset", "GET_DATASET_LIST", params.query())
287            .await
288    }
289
290    /// One dataset with its filters (`refDataset` with an ID, データセット参照).
291    /// Takes a dataset ID or [`DatasetParams`].
292    ///
293    /// # Errors
294    ///
295    /// [`EstatError::Api`] with `300` when there is no dataset with that ID.
296    /// Otherwise the same as [`stats_list`](Self::stats_list).
297    pub async fn dataset(
298        &self,
299        params: impl Into<DatasetParams>,
300    ) -> Result<RefDataset, EstatError> {
301        let params = params.into();
302        self.request("refDataset", "REF_DATASET", params.query())
303            .await
304    }
305
306    /// Registers, updates or deletes a dataset (`postDataset`, データセット登録).
307    ///
308    /// This changes data on e-Stat under your application ID. e-Stat answers
309    /// this call in XML only, and it is sent to `postDataset` next to the
310    /// `json` directory of the base URL.
311    ///
312    /// # Errors
313    ///
314    /// [`EstatError::Api`] with `101` to `104` for missing or invalid
315    /// parameters, `301` when the dataset belongs to another application ID,
316    /// `302` when the filters select nothing. Otherwise the same as
317    /// [`stats_list`](Self::stats_list).
318    pub async fn post_dataset(
319        &self,
320        params: &PostDatasetParams,
321    ) -> Result<PostDataset, EstatError> {
322        let base = self
323            .base_url
324            .strip_suffix("/json")
325            .unwrap_or(&self.base_url);
326        let url = endpoint(base, "postDataset")?;
327        let request = self.client.post(url).form(&self.pairs(params.query()));
328        let (status, text) = self.send(request).await?;
329        PostDataset::from_xml(status, &text)
330    }
331
332    async fn request<T: DeserializeOwned>(
333        &self,
334        path: &str,
335        root: &str,
336        query: &[(String, String)],
337    ) -> Result<T, EstatError> {
338        let url = self.url(path, query)?;
339        let (status, text) = self.send(self.client.get(url)).await?;
340        parse_json(status, &text, root)
341    }
342
343    async fn send(
344        &self,
345        mut request: reqwest::RequestBuilder,
346    ) -> Result<(u16, String), EstatError> {
347        if let Some(timeout) = self.timeout {
348            request = request.timeout(timeout);
349        }
350        let response = request.send().await.map_err(EstatError::connection)?;
351        let status = response.status().as_u16();
352        let text = response.text().await.map_err(EstatError::connection)?;
353        Ok((status, text))
354    }
355
356    /// `appId`, `lang` and the parameters.
357    fn pairs(&self, query: &[(String, String)]) -> Vec<(String, String)> {
358        let mut pairs = vec![("appId".to_string(), self.app_id.clone())];
359        if let Some(lang) = self.lang {
360            pairs.push(("lang".into(), lang.code().into()));
361        }
362        pairs.extend_from_slice(query);
363        pairs
364    }
365
366    fn url(&self, path: &str, query: &[(String, String)]) -> Result<Url, EstatError> {
367        let mut url = endpoint(&self.base_url, path)?;
368        url.query_pairs_mut().extend_pairs(self.pairs(query));
369        Ok(url)
370    }
371}
372
373fn endpoint(base: &str, path: &str) -> Result<Url, EstatError> {
374    Url::parse(&format!("{base}/{path}"))
375        .map_err(|e| EstatError::InvalidArgument(format!("base url: {e}")))
376}
377
378/// Checks `RESULT` and reads the body under `root`.
379fn parse_json<T: DeserializeOwned>(status: u16, text: &str, root: &str) -> Result<T, EstatError> {
380    let success = (200..300).contains(&status);
381    let body = match serde_json::from_str::<Value>(text) {
382        Ok(Value::Object(mut map)) if map.contains_key(root) => map.remove(root),
383        _ if !success => {
384            return Err(EstatError::HttpStatus(status, text.to_string()));
385        }
386        Ok(_) => None,
387        Err(e) => return Err(EstatError::JsonParse(e)),
388    };
389    let Some(body) = body else {
390        return Err(EstatError::UnexpectedResponse(format!(
391            "no {root} in the body"
392        )));
393    };
394    let result = body
395        .get("RESULT")
396        .ok_or_else(|| EstatError::UnexpectedResponse(format!("no RESULT in {root}")))?;
397    let result = ApiResult::deserialize(result).map_err(EstatError::JsonParse)?;
398    if result.status >= 100 {
399        return Err(EstatError::Api {
400            status: result.status,
401            message: result.error_msg,
402        });
403    }
404    T::deserialize(body).map_err(EstatError::JsonParse)
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410
411    #[test]
412    fn builds_urls() {
413        let api = EstatApi::with_app_id("a&b")
414            .with_base_url("https://example.com/json/")
415            .with_lang(Lang::English);
416        let params = StatsListParams::new().search_word("東京 AND 人口");
417        let url = api.url("getStatsList", params.query()).unwrap();
418        assert_eq!(
419            url.as_str(),
420            "https://example.com/json/getStatsList?appId=a%26b&lang=E&searchWord=%E6%9D%B1%E4%BA%AC+AND+%E4%BA%BA%E5%8F%A3"
421        );
422        let url = EstatApi::with_app_id("k")
423            .url("getMetaInfo", MetaInfoParams::new("0003").query())
424            .unwrap();
425        assert_eq!(
426            url.as_str(),
427            "https://api.e-stat.go.jp/rest/3.0/app/json/getMetaInfo?appId=k&statsDataId=0003"
428        );
429        assert_eq!(Lang::Japanese.code(), "J");
430    }
431
432    #[test]
433    fn rejects_bad_base_url() {
434        let api = EstatApi::with_app_id("k").with_base_url("not a url");
435        let error = api.url("getStatsList", &[]).unwrap_err();
436        assert!(error.to_string().starts_with("invalid argument: base url"));
437    }
438
439    #[test]
440    fn app_id_from_env() {
441        let api = EstatApi::from_app_id(Some("id".into())).unwrap();
442        assert_eq!(api.app_id, "id");
443        for missing in [None, Some(String::new())] {
444            let error = EstatApi::from_app_id(missing).unwrap_err();
445            assert_eq!(
446                error.to_string(),
447                "invalid argument: ESTAT_APP_ID is not set"
448            );
449        }
450        // Depends on the environment; either way it must not panic
451        let _ = EstatApi::from_env();
452    }
453
454    #[test]
455    fn debug_hides_the_app_id() {
456        let api = EstatApi::with_app_id("secret").with_timeout(Duration::from_secs(5));
457        let debug = format!("{api:?}");
458        assert!(!debug.contains("secret"));
459        assert!(debug.contains("5s"));
460        let debug = format!("{:?}", api.with_client(reqwest::Client::new()));
461        assert!(debug.contains("timeout: None"));
462    }
463}