Last active
December 1, 2023 13:33
-
-
Save avinash010/7b35608bffcf5226b575da7e1315ffa3 to your computer and use it in GitHub Desktop.
reqwest_car_api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[tokio::main] | |
async fn main() { | |
let json_data = r#" | |
{ | |
"name": "figo", | |
"brand": "Ford", | |
"price_range": "2-3lacs", | |
"car_type": "hatchback" | |
} | |
"#; | |
let response = add_cars(json_data).await; | |
println!("response = {:#?}", response); | |
} | |
async fn add_cars(json_data: &str) -> Result<String, Box<dyn std::error::Error>> { | |
let username = "qxf2"; | |
let password = "qxf2"; | |
let client = reqwest::Client::new(); | |
let response = match client.post("http://127.0.0.1:5000/cars/add") | |
.basic_auth(username, Some(password)) | |
.header(reqwest::header::CONTENT_TYPE, "application/json") | |
.body(json_data.to_string()) // Convert json_data to String and send it as the body | |
.send() | |
.await { | |
Ok(res) => res, | |
Err(err) => { | |
return Err(Box::new(err)); | |
} | |
}; | |
let body = match response.text().await { | |
Ok(text) => text, | |
Err(err) => { | |
return Err(Box::new(err)); | |
} | |
}; | |
Ok(body) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[tokio::main] | |
async fn main() { | |
let cars = get_cars().await; | |
println!("cars = {:#?}", cars); | |
} | |
async fn get_cars() -> Result<String, Box<dyn std::error::Error>> { | |
let username = "qxf2"; | |
let password = "qxf2"; | |
let client = reqwest::Client::new(); | |
let response = match client.get("http://127.0.0.1:5000/cars") | |
.basic_auth(username, Some(password)) | |
.send() | |
.await { | |
Ok(res) => res, | |
Err(err) => { | |
return Err(Box::new(err)); | |
} | |
}; | |
let body = match response.text().await { | |
Ok(text) => text, | |
Err(err) => { | |
return Err(Box::new(err)); | |
} | |
}; | |
Ok(body) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment