Getting started with Polygon.io and Rust.
Published on Jan 25, 2025, by TradeTinkerer
Connecting to the Polygon.io API.
Before you can do anything with the Polygon.io API, you first have to authenticate.
Authentication.
There are two different ways to use you API token to authenticate with the Polygon.io API.
The first way to authenticate, is to pass your API token in the query string of the URL.
https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-01-09/2023-02-10?adjusted=true&sort=asc&apiKey={token} The second (and my preferred way), is to use a Authorization header, like this:
Authorization: Bearer {token} In rust passing the token in the URL, could look something like this:
let url_with_token = format!("https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-01-09/2023-02-10?adjusted=true&sort=asc&apiKey={}", env::var("POLYGON_API_KEY").unwrap());
let response = reqwest::get(url_with_token)
.await
.unwrap()
.json::<AggregatedBars>()
.await;
match response {
Ok(aggregated_bars) => {
info!("Aggregated Bars with auth token in the url:");
for bar in aggregated_bars.results {
info!("{:?}", bar);
}
}
Err(e) => {
error!("API response cannot be parsed! {}", e)
}
}; First we add the token to the URL, and then we use the reqwest crate to make a simple get request to the Polygon.io API.
We parse the resulting JSON to a struct.
Using a Authorization header is pretty similar:
let token = "Bearer ".to_owned() + &env::var("POLYGON_API_KEY").unwrap();
let client = reqwest::Client::new();
let response = client
.get(url)
.header("Authorization", token)
.send()
.await
.unwrap()
.json::<AggregatedBars>()
.await;
match response {
Ok(aggregated_bars) => {
info!("Aggregated Bars with auth token in the header:");
for bar in aggregated_bars.results {
info!("{:?}", bar);
}
}
Err(e) => {
error!("API response cannot be parsed! {}", e)
}
}; As you can see the code is similar.
The full code for these examples can be found on Github.