Skip to content

Instantly share code, notes, and snippets.

@githubdebugger
Created September 2, 2024 14:56
Show Gist options
  • Save githubdebugger/15774b881819d4d6a07cea80a7fddfae to your computer and use it in GitHub Desktop.
Save githubdebugger/15774b881819d4d6a07cea80a7fddfae to your computer and use it in GitHub Desktop.
fetch_and_parse_json
async fn fetch_and_parse_json(
client: &Client,
api_key: &str,
access_token: &str,
symbols: &[&str],
) -> Result<Option<DataFrame>> {
let url = "https://api.kite.trade/quote";
let start = Instant::now();
let params: Vec<(&str, &str)> = symbols.iter().map(|&s| ("i", s)).collect();
let response: Value = client
.get(url)
.header("X-Kite-Version", "3")
.header(
"Authorization",
format!("token {}:{}", api_key, access_token),
)
.query(&params)
.send()
.await?
.json()
.await?;
println!("JSON fetched in {}ms", start.elapsed().as_millis());
let json_data = match response.get("data") {
Some(data) => data,
None => {
println!("No 'data' field found in the API response.");
return Ok(None);
}
};
if json_data.as_object().map_or(true, |obj| obj.is_empty()) {
println!("No data received from the API.");
return Ok(None);
}
let start = Instant::now();
let json = serde_json::to_string(&json_data)?;
println!("JSON parsed in {}ms", start.elapsed().as_millis());
let start = Instant::now();
let df = JsonReader::new(Cursor::new(json))
.with_json_format(JsonFormat::Json)
.infer_schema_len(Some(NonZeroUsize::new(100).unwrap()))
.finish()?;
println!("DataFrame created in {}ms", start.elapsed().as_millis());
Ok(Some(df))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment