Send and receive JSON
For Rust developers talking to a JSON API
You post a Rust struct as JSON and read the answer back into another struct, using serde on both ends.
Before you start
You need Rust with Cargo. fibre_http comes from crates.io:
fibre_http = "0"Set up the project#
Start a new binary crate.
Put this in the [dependencies] section of Cargo.toml:
[]
= { = "0", = ["json"] }
= { = "1", = ["derive"] }
= { = "1", = ["full"] }The program#
httpbin.org's /post endpoint sends back whatever JSON it received under a json field. That makes it a handy stand-in for a real API. Replace src/main.rs with this:
use AsyncClient;
use ;
async
Run it:
What each part does#
json(&todo) on the request turns the struct into JSON with serde and sets Content-Type: application/json. Any type that implements Serialize works.
json() on the response reads the whole body and turns it into any type that implements Deserialize. Fields the struct does not name are skipped, which is why Echo only needs json out of httpbin's longer answer.
If the body is not valid JSON for that type, json() returns an error instead of a half-filled struct.
Where to go next#
The usage guide covers the other ways to send a body: https://github.com/excsn/fibre/blob/main/http/README.USAGE.md
