Function json_request::request [] [src]

pub fn request<S, D>(method: Method, url: &str, data: Option<S>) -> Result<Option<D>> where S: Encodable, D: Decodable

Make an HTTP request

The third parameter of request, data, will be automatically serialized as JSON and set as the request body before making the request. The wrapped result will be decoded from any 2xx JSON response. For the automatic encoding to work, the data type must implement rustc_serialize::Encodable, and the result type must implement rustc_serialize::Decodable. This can usually be achieved with #[derive(RustcEncodable)] and #[derive(RustcDecodable)].

Example

extern crate rustc_serialize;
extern crate json_request;

use json_request::{request, Method};

#[derive(Debug, RustcEncodable)]
struct RequestData {
    ping: bool
}

#[derive(Debug, RustcDecodable)]
struct ResponseData {
    pong: bool
}

let data = RequestData { ping: true };
let res = request(Method::Post, "http://example.com/ping", Some(data));
// Request returns a Result<Option<D>>; hence, two unwrap calls
let pong: ResponseData = res.unwrap().unwrap();

Alternatively, if you don't want to specify the binding type, pass the type parameter to request.

let res = request::<_, ResponseData>(Method::Post, "http://example.com/ping", Some(data));
let pong = res.unwrap().unwrap();