loading...

Day37:Post JSON to API with surf - 100DayOfRust

0xbf profile image Bo ・1 min read

We can use Rust's surf crate to post application/json type data to API:

Cargo.toml:

[dependencies]
async-std = "1.4.0"
serde_json = "1.0.48"
surf = "1.0.3"

main.rs

use async_std::task;
use serde_json::json;
use surf;

fn main() {
    let apiurl = "https://httpbin.org/post";
    let data = json!({
        "key": "key",
        "msg": "hello world",
        "receivers": vec!["@mario", "@link"]
    });

    task::block_on(async {
        println!("Send url to {}", apiurl);
        let mut res = surf::post(apiurl)
                           .body_json(&data).unwrap().await.unwrap();

        println!("Status:\t{} \nInfo:\t{}\n", 
                 res.status(), 
                 res.body_string().await.unwrap());
    });
}

Run it:

Send url to https://httpbin.org/post
Status: 200 OK 
Info:   {
  "args": {}, 
  "data": "{\"key\":\"key\",\"msg\":\"hello world\",\"receivers\":[\"@mario\",\"@link\"]}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "deflate, gzip", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "Transfer-Encoding": "chunked", 
    "User-Agent": "curl/7.68.0-DEV isahc/0.7.6", 
    "X-Amzn-Trace-Id": "Root=1-5e5aaf42-59eefa3ec932007880a294f8"
  }, 
  "json": {
    "key": "key", 
    "msg": "hello world", 
    "receivers": [
      "@mario", 
      "@link"
    ]
  }, 
  "origin": "63.80.139.31", 
  "url": "https://httpbin.org/post"
}

Discussion

pic
Editor guide