Expand description
fred_api makes requests to FRED to download
economic data, caching it to a data-store so that repeated requests to FRED can be
avoided.
§Requirements
-
FRED_API_KEYenvironment variable can be set or supplied directly. -
FRED_CACHEis the directory to place the cache. It can also be set as an environment variable or supplied directly.
§Code Example
use fred_api::*;
use sled::{Db, IVec};
use tokio;
#[tokio::main]
pub async fn main() {
// Set the path to the cache. The cache stores the response bytes as is, keyed by
// the `RequestSpec`.
let cache: sled::Db = sled::open(fred_cache(None).unwrap()).unwrap();
// See the FRED API documentation to build requests. In these docs each request
// category has an example XML request such as:
//
// https://api.stlouisfed.org/fred/series/observations?series_id=GNPCA&api_key=abcdefghijklmnopqrstuvwxyz123456
// ------------------------------------
// The first function argument is underlined section including the "&" or the "?"
// preceding "api_key". If the second function argument is None, the API key is read
// from the environment variable FRED_API_KEY.
let req = build_request("series/observations?series_id=GNPCA&", None).unwrap();
// Lookup options are Lookup::FredOnly, Lookup::CacheOnly or
// Lookup::FredOnCacheMiss. Successful FRED responses are always cached.
let bytes: IVec = send_request(&req, Lookup::FredOnCacheMiss, &cache).await.unwrap();
let mut field_iter = FieldIter::new("observation", vec!("date", "value"), bytes);
let fields = field_iter.next().unwrap().unwrap();
assert_eq!("1971-04-01", fields[0]);
assert_eq!(0.850603488248666, fields[1].parse::<f32>().unwrap());
}Macros§
- src
- Create a
DebugErrtype, which includes information about the locations of the error.
Structs§
- Debug
Err - Use the
src!()macro to build this error. - Field
Iter - Request
Spec - A request spec is the middle-part of a FRED request Uri with the base part removed from the left and the API key removed from the right.
Enums§
- Lookup
- Determines the lookup method. A successful request will always write to the cache.
Functions§
- build_
request - Build a request from the mid-part of the URL.
- cache_
request - Non-async request to cache only.
- fred_
cache - Retrieves
FRED_CACHEenvironment variable if set or fails. - send_
request - Send a request to FRED or the cache, using the lookup method to determine procedure.