api
api provides a set of utilities for defining
HTTP API on the client side without worrying about
the actual HTTP client (until you send the
request!).
Api trait
api::Api is a trait used to define a remote API.
The developer must implement it for the struct
that represents the API endpoint.
For our examples, we'll create a simple client for httpbin
and its endpoint /delay:n (delays responding n seconds
and returns some information about the request).
Api has three associated types:
-
Bodyis used to generate the request body and it must implement the traitstd::io::Read. If the endpoint doesn't require a bodystd::io::Emptyshould be used. -
Replydefines the response that we expect to receive from the API. -
Errordefines all the expected errors that we could get when the response is received.
First of all, we need to define the request and the response.
/delay/:n has only one parameter in the path and we'll only care about the fields origin and headers in the JSON response
(we'll use serde_json to parse the response's body).
extern crate api;
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
// request for /delay/:n
// it's a subset of the available data
Then, we can start defining how the HTTP request will look like
implementing the trait Api for Delay.
We'll send a GET request to /delay/:n and :n will be
replaced with the value in Delay.delay.
Now, we need to create the reply Info from
the HTTP response represented by the trait HttpResponse.
api has a trait Client to create an adapter for the actual HTTP client, and it implements it for hyper::Client.
Client has a method send that accepts the base URL for the API
and the request.
extern crate hyper;
use Client;
...
The full code is in examples/httpbin.rs
(run cargo run --example=httpbin --features=use-hyper).