Last active
February 14, 2022 13:25
-
-
Save ugovaretto/8460134cc1510c880deebfec75ba9f26 to your computer and use it in GitHub Desktop.
Create web service that sends a request to github 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
[package] | |
name = "rocket_reqw" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
rocket = "0.4" | |
serde = {version = "1", features = ["derive"]} | |
serde_json = "1" | |
reqwest = {version = "0.11", features = ["blocking", "native-tls", "json"]} |
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
// Author: Ugo Varetto | |
// Updated version of: https://www.shawntabrizi.com/code/combining-rocket-with-reqwest-to-call-an-api-with-rust/ | |
// Also returns JSON record for valid users. | |
#![feature(decl_macro)] | |
use rocket::http::RawStr; | |
use reqwest::blocking::Client; | |
use reqwest; | |
use std::time::Duration; | |
use serde_json; | |
use serde_json::Value; | |
#[macro_use] extern crate rocket; | |
#[get("/")] | |
fn index() -> &'static str { | |
"Navigate to http://localhost:8000/check/<type your GitHub name here> to check that everything is working!" | |
} | |
#[get("/check/<user>")] | |
fn check(user: &RawStr) -> Result<String, Box<dyn std::error::Error>> { | |
let request_url = format!("https://api.github.com/users/{}", user); | |
let client = Client::builder() | |
.use_native_tls() | |
.timeout(Duration::new(5, 0)) | |
// without user agent it returns 403 | |
.user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36") | |
.build()?; | |
let resp = client.get(request_url).send()?; | |
if resp.status().is_success() { | |
let pp = if let Ok(r) = resp.text() { | |
let j: Value = serde_json::from_str(r.as_str())?; | |
serde_json::to_string_pretty(&j)? | |
} else {String::new()}; | |
Ok(format!("\"{}\" is a user\n\n{}", user, pp)) | |
} | |
else { Ok(format!("\"{}\" is NOT a user", user))} | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
rocket::ignite().mount("/", routes![index, check]).launch(); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment