Crate wclient[][src]

Expand description

Simple Web Client for Rust

wclient is a lightweigh HTTP web client inspired on Python Requests.

It allows to send HTTP requests and receive the responses.

Features

  • HTTP 1.1 Request and Response over plain TCP/IP and TLS
  • HTTP Session to share configuration and a cookie jar among requests
  • HTTP 1.1 Single Body
  • HTTPS (v1.1) with default site certificate verification (only with host CA certificates)
  • HTTPS custom site certificate validation (local directory or certificate chain) in *.pem format
  • HTTPS client certificate authentication
  • HTTP Connection pooling
  • AuthManager trait fo authenticating requests (Athentication header)
  • HttpBasicAuth for Athentication: Basic

Future Features

  • Multipart
  • HTTP 2.0

User Guide

You can find some examples at GitHub project examples.

To create a Request, it is needed a RequestBuilder.

The RequestBuilder has constructor functions for each HTTP method that requires the target url string: connect, delete, get, head, options, patch, post and put.

The ‘RequestBuilder’ allows to add name/value data for:

  • Headers through the functions header for a single header or headers for a set of headers. Header names are case-insensitive.
  • Parameters through the functions param for a single parameter or params for a set of parameters. Parameter names are case-sensitive.
  • Cookies through the functions cookie for a single cookie or cookies for a set of cookies. Cookie names are case-sensitive.

Also, the RequestBuilder allows to set HttpConfig configurations through the config function. Finally, to create a Request object, it has to be used the build member function of RequestBuilder.

Next example shows how to construct a GET request to the URL http://web.myservice.com/user?id=12345&name=John

use wclient::RequestBuilder;

let request = RequestBuilder::get("http://web.myservice.com/user")
    .header("Accept", "application/json")
    .param("id", "12345")
    .param("name", "John")
    .build(); 

The Request body can be set as a Vec<u8> using the function body or the function json with a JSON Object value form the crate json.

use wclient::RequestBuilder;
use json::object;
let data = object! {
   name: "John",
   surname: "Smith"
};
 
let mut request = RequestBuilder::post("http://web.myservice.com/user")
    .header("Accept", "application/json")
    .param("id", "12345")
    .json(&data)
    .build();
// The Response
 
let response = request.send().unwrap();
// Check status code is 200 Success
assert_eq!(response.status_code(), 200);
let result_json = response.json();
// Check the request had JSON content
assert!(result_json.is_ok());
let result_data = result_json.unwrap();
// Print JSON object
println!("{:?}", result_data.as_str() )
 

After, created, the send function sends the request message to the target URL and returns a Result<Response, Error> value.

HTTP Connection configuration

The RequestBuilder has a function to set a HttpConfig. Currently, it can be configured:

  • The Root CA certificates to authenticate the server with HTTPS, see HttpsVerify
  • The client certificate to be authenticated against the serve with HTTPS, see HttpsCert

Server authentication

By default, wclientuses the system CA certificates directory (for example, /etc/ssl/certs). Trusted CA can be also passed as a .pem file path or a directory containing certificate files:

 
use wclient::RequestBuilder;
use wclient::config::{HttpsVerify, HttpConfigBuilder};
 
let config = HttpConfigBuilder::default()
   .verify(HttpsVerify::Path(String::from("./config/server.pem")))
   .build();
 
let request = RequestBuilder::get("https://web.myservice.com/user")
    .header("Accept", "application/json")
    .config(&config);
 

Client authentication

The client app can be authenticated against the HTTPS using a certificate and the assotiated private key by using the HttpsCert enum.

NOTE: If the client certificate is self-signed or signed by CA that is not in the system or custom CA certificates list, the client certificate must contain the certificate chain to the root CA. In this case, the fist certificate in the file must be the client certificate.

 
use wclient::RequestBuilder;
use wclient::config::{HttpsCert, HttpConfigBuilder};
 
let config = HttpConfigBuilder::default()
   .cert(HttpsCert::CertKey{cert: String::from("/path/client.crt"), key: String::from("/path/client.key")})
   .build();
 
let request = RequestBuilder::get("https://web.myservice.com/user")
    .header("Accept", "application/json")
    .config(&config)
    .build();
 

HTTP Sessions

The Session type allows to store common configurations and share cookies through an internal or custom set cookie jar. The Session object also makes connection pooling, reusing the same connection to send different requests (if server allows it).

Session values are constructed through the SessionBuilder builder that allows to set a HttpConfig value and a shared pointer to a shared CookieJar trait implementation.

 
use wclient::SessionBuilder;
use wclient::config::{HttpsCert,HttpConfigBuilder};
 
 
let config = HttpConfigBuilder::default()
   .cert(HttpsCert::CertKey{cert: String::from("/path/client.crt"), key: String::from("/path/client.key")})
   .build();
     
let session = SessionBuilder::new()
   .config(&config)
   .build();
 

Once built, the Session value allows to create RequestBuilder for each HTTP method that shares the HttpConfig and CookieJar. The RequestBuilder can override the shared config and cookie jar.

use wclient::SessionBuilder;
 
let mut session = SessionBuilder::new().build();
 
let mut request = session.get("https://service.com/user")
    .header("Accept", "application/json")
    .build();
 
let response = request.send();

Authorization

RFC 7235 defines the WWW-Authenticate response header where a server is requesting the client to authenticate the request. The AuthManager trait defines the functions to process these kind of authenticate headers and generate the proper headers(typically an Authorization header).

wclientprovides HttpBasicAuth implementation of AuthManager trait for Basic authentication which uses a base64 encoded user:password as header:

Authorization: Basic YW55IGNhcm5hbCBwbGVhc3U=

The SessionBuilder and RequestBuilder have a method ‘auth’ to set an AuthManage. The AuthManager has to be contained in a thread-safe Arc ref-counter and inside a Mutex:

 use wclient::auth::HttpBasicAuth;
 use wclient::RequestBuilder;
 use std::sync::{Arc, Mutex}; 
 
 let manager = Arc::new(Mutex::new(HttpBasicAuth::new("wclient", "user,1234")));

 let mut request = RequestBuilder::get("http://localhost:8000/users/12/")
                   .auth(manager)
                   .build();
 let response = request.send();
 

Modules

HTTP Authentication module

HTTP configuration settings

Structs

HTTP request

Helper builder for Request

HTTP Response An HTTP Response is formed by:

HTTP session used to share configuration and cookies among different requests and responses

Session Builder class.

Enums

HTTP Request Method

Constants

HTTP 100 CONTINUE status code

HTTP 101 SWITCHING_PROTOCOLS status code

HTTP 200 OK status code

HTTP 201 CREATED status code

HTTP 202 ACCEPTED status code

HTTP 204 NO CONTENT status code

HTTP 205 RESET CONTENT status code

HTTP 400 BAD REQUEST status code

HTTP 401 UNAUTHORIZED status code

HTTP 402 BAD REQUEST status code

HTTP 404 NOT FOUND status code

HTTP 405 METHOD NOT ALLOWED status code

HTTP 406 NOT ACCEPTABLE status code

HTTP 408 REQUEST_TIMEOUT status code

HTTP 500 INTERNAL_SERVE_ERROR status code

HTTP 501 NOT IMPLEMENTED status code

Type Definitions

HTTP Response status code

List of Set-Cookie headers in a HTTP Response