Created
December 17, 2022 18:47
-
-
Save kenyipp/6e873aa4fae6d9a3fa8441b2bc9a1530 to your computer and use it in GitHub Desktop.
Using the "reqwest" and "serde" crates to fetch and Serialize/ Deserialize the data from typicode.com
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
use serde::{ Serialize, Deserialize }; | |
// Allowed the main function to be async, specifies our async code will be executed by the tokio runtime | |
#[tokio::main] | |
async fn main() -> Result<(), reqwest::Error> { | |
// print!("{:#?}", add_todos().await); | |
Ok(()) | |
} | |
async fn add_todos() -> Result<Todo, reqwest::Error> { | |
let client = reqwest::Client::new(); | |
let body = | |
serde_json::json!({ | |
"userId": 1, | |
"title": "Subscribe to Let's Get Rusty".to_owned(), | |
"completed": false | |
}); | |
let response: Todo = client | |
.post("https://jsonplaceholder.typicode.com/todos") | |
.json(&body) | |
.send().await? | |
.json().await?; | |
return Ok(response); | |
} | |
async fn get_todos() -> Result<Vec<Todo>, reqwest::Error> { | |
let client = reqwest::Client::new(); | |
let todos: Vec<Todo> = client | |
.get("https://jsonplaceholder.typicode.com/todos?userId=1") | |
.send().await? | |
.json().await?; | |
return Ok(todos); | |
} | |
#[derive(Debug, Serialize, Deserialize)] | |
struct Todo { | |
#[serde(rename = "userId")] | |
user_id: i32, | |
id: Option<i32>, | |
title: String, | |
completed: bool, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment