Curl to Reqwest

Hi Rust fam, I'm trying to convert a Curl command to Rust using Reqwest and then print one of the parameters in the JSON response. I was wondering if you could help with the code below:

Curl Command (Convert to Rust Reqwest Format)

curl -X GET 'https://lookups.twilio.com/v1/PhoneNumbers/+15108675310?Type=carrier' \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN

Then it'll respond with the JSON below where I would like to print the value of "type" which is "mobile"

{
  "caller_name": null,
  "carrier": {
    "error_code": null,
    "mobile_country_code": "310",
    "mobile_network_code": "456",
    "name": "verizon",
    "type": "mobile"
  },
  "country_code": "US",
  "national_format": "(510) 867-5310",
  "phone_number": "+15108675310",
  "add_ons": null,
  "url": "https://lookups.twilio.com/v1/PhoneNumbers/+15108675310"
}

Appreciate any help you can give me, thanks!

This is a GET request with basic authentication. You can use RequestBuilder::basic_auth method for basic authentication.

To parse JSON from response you can use Response::json. This requires a structure that implements Deserialize, like this.

#[derive(Deserialize)]
struct PhoneNumberResponse {
    carrier: Carrier,
}

#[derive(Deserialize)]
struct Carrier {
    // type is a reserved keyword, so it needs to be prefixed with r#
    r#type: String,
}

Deserialize comes from serde, see Using derive ยท Serde for instructions for using it.

So would this work for sending the request?

let client = reqwest::Client::new();
let resp = client.get("https://lookups.twilio.com/v1/PhoneNumbers/+15108675310?Type=carrier")
    .basic_auth("TWILIO_ACCOUNT_SID", Some("TWILIO_AUTH_TOKEN"))
    .send()
    .await?;

And then will this work to extract the value?

#[derive(Deserialize)]
struct PhoneNumberResponse
{
    carrier: Carrier,
}

#[derive(Deserialize)]
struct Carrier
{
    r#type: String,
}

async fn main()
{
  let a: PhoneNumberResponse = resp.unwrap();
  let b = a["carrier"];
  let c : Carrier = b.unwrap();
  println!("{:?}", c["type"].as_str().unwrap());
}

That's the general idea, although you would use a.carrier and c.r#type because they are fields and not keys in a dictionary.

Thanks for the help guys.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.