Comment on page
Rust
In Rust, we'll use the
reqwest
library to send HTTP requests. Here's how you can use the book search API with Rust:First, add the following dependencies in your
Cargo.toml
file:[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Then, you can use the following code to make the API request:
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use serde::Deserialize;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[derive(Deserialize)]
struct Book {
title: String,
author: String,
}
let url = "https://api.promptjoy.com/api/mVMCpq";
let api_key = env::var("PROMPTJOY_API_KEY").unwrap();
let mut headers = HeaderMap::new();
headers.insert("x-api-key", HeaderValue::from_str(&api_key).unwrap());
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
let client = reqwest::Client::new();
let res = client.post(url)
.headers(headers)
.json(&serde_json::json!({"query": "your_search_term"}))
.send()
.await?;
let books: Vec<Book> = res.json().await?;
for book in books {
println!("Title: {}, Author: {}", book.title, book.author);
}
Ok(())
}
Replace
"your_search_term"
with the book you're searching for. This function will return a vector of books.Remember to handle exceptions and errors as needed in your actual application code.
Note: This example uses the
serde
and serde_json
crates for deserialization of the JSON response. The tokio
crate is used as the async runtime. Also, the API key is retrieved from environment variables for security reasons. Ensure that you've set the PROMPTJOY_API_KEY
environment variable in your environment where this code will be executed.Last modified 5mo ago