typestar

Posting a body in Rust

A POST with JSON, headers and a bearer token, built up on the request.

use serde::Serialize;

#[derive(Serialize)]
struct RunResult {
    lang: &'static str,
    tpm: u32,
    accuracy: f64,
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::Client::new();
    let payload = RunResult { lang: "rust", tpm: 104, accuracy: 97.5 };

    let response = client
        .post("https://typestar.io/api/results")
        .bearer_auth("token-goes-here")
        .header("X-Client", "typestar-cli")
        .json(&payload)
        .send()
        .await?;

    println!("{}", response.status());
    Ok(())
}

How it works

  1. json sets the body and the content type together.
  2. header adds one header; bearer_auth is the shorthand.
  3. send is where the request actually goes out.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
488
Tokens
139
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 3 of 5 in Requests with reqwest, step 9 of 12 in CLI tools & HTTP clients.

← Previous Next →