Giter VIP home page Giter VIP logo

rest_client's Introduction

NOTE: Author here - this library is now really out of date, and does not compile anymore. Please don't try to build anything new on top of it.

It won't be updated until I find some time to dig into Rust again and get up to speed with the latest version of the language.

Rust REST Client

A simple HTTP and REST client for Rust, inspired by Ruby's rest-client.

The goal: make common REST requests with the fewest lines of code.

Built on top of the Hyper HTTP library.

Full API Documentation

Usage

First, add the dependency to your Cargo.toml:

[dependencies.rest_client]

git = "https://github.com/gtolle/rest_client"

Then, cargo update, write your code, cargo build, cargo run, etc.

extern crate rest_client;
extern crate rustc_serialize;

// One simple 'use' to get all the functionality, plus the 'extern crate'.
use rest_client::RestClient;
use rustc_serialize::json;

fn main() {
    
    // A simple GET is just a GET. You can print the response struct (it supports Show).
    
    println!("{}", RestClient::get("http://example.com/resource").unwrap());
    
    // You can use an array of tuples to create a GET with query parameters.
    // The client handles all the URL-encoding and escaping for you.
    
    println!("{}", RestClient::get_with_params("http://example.com/resource",
                                               &[("id", "50"), ("foo", "bar")]).unwrap());

    // You can also use an array of tuples to create a POST with form parameters. 
    // The client sets the content-type to application/x-www-form-urlencoded for you.
    
    println!("{}", RestClient::post_with_params("http://example.com/resource",
                                                &[("param1", "one"), 
                                                  ("param2", "two")]).unwrap());

    // You can POST a string or a JSON object with just a string and a MIME type.
    
    let object = TestStruct {
        data_int: 1,
        data_str: "toto".to_string(),
        data_vector: vec![2,3,4,5],
    };
    
    println!("{}", RestClient::post("http://example.com/resource",
                                    &json::encode(&object).unwrap(), 
                                    "application/json").unwrap());

    // PUT and PATCH are supported as well, just like POST.
    
    // You can delete a resource with a simple DELETE. delete_with_params works too.
    
    println!("{}", RestClient::delete("http://example.com/resource").unwrap());
    
    /*
      The response struct has a few fields
      code (a simple integer)
      body (a string)
      status (a typed response code, from Hyper)
      headers (typed headers from Hyper)
    */
    
    let response = RestClient::get("http://example.com/resource").unwrap();
    
    println!("{}", response.code); // -> 404
    
    for header in response.headers.iter() {
        println!("{}", header); // -> (Cache-Control, max-age=604800) ...
    }
    
    println!("{}", response.to_string());				  
    
    /*
      All of the underlying errors are passed up through 
      the RestError struct in the Result.
      
      pub enum RestError {
        UrlParseError(ParseError),
        HttpRequestError(HttpError),
        HttpIoError(IoError)
      }
    */
}

#[deriving(Decodable, Encodable)]
pub struct TestStruct  {
    data_int: u8,
    data_str: String,
    data_vector: Vec<u8>,
}

Examples

    println!("{}", RestClient::get("http://www.reddit.com/hot.json?limit=1").unwrap());

    let response = RestClient::get("http://www.reddit.com/hot.json?limit=1").unwrap();
    
    let response_json = Json::from_str(&response.body).unwrap();

    println!("{}", response_json.as_object().unwrap()
                                .get(&"data".to_string()).unwrap().as_object().unwrap()
                                .get(&"children".to_string()).unwrap());

    println!("{}", RestClient::post_with_params("http://www.reddit.com/api/login.json", 
                                                &[("api_type", "json"),
                                                  ("user", "myusername"),
                                                  ("passwd", "mypassword"),
                                                  ("rem", "True")]).unwrap());

TODO

  • Add support for custom request headers
  • Built-in JSON serialization?
  • Examine what parts of Hyper should get re-exposed
  • Add support for cookies
  • Extend hyper to support basic auth (lots of APIs need it)
  • Multipart POST
  • Unit tests
  • Testing in real applications
  • Refactoring

rest_client's People

Contributors

brianloveswords avatar gtolle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rest_client's Issues

Releasing?

Do you plan releasing it to cargo? When running in production I think it would be easier instead having to import the github repository.

compile error (incopatibility to hyper?)

when building with cargo I get:

/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:86:29: 86:41 error: no associated item named `new` found for type `hyper::client::Request<'_>` in the current scope
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:86         let mut req = match Request::new(method, url) {
                                                                                                                  ^~~~~~~~~~~~
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:93:17: 93:34 error: the type of this value must be known in this context
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:93                 req.headers_mut().set(ContentLength(body.len() as u64)),
                                                                                                      ^~~~~~~~~~~~~~~~~
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:115:23: 115:57 error: the type of this value must be known in this context
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:115                 match req_started.write(body.as_bytes()) {
                                                                                                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:128:15: 128:50 error: the type of this value must be known in this context
/Users/philipp/.cargo/git/checkouts/rest_client-0374f799cdee3e12/master/src/lib.rs:128         match resp.read_to_string(&mut resp_body) {
                                                                                                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

my Cargo.toml:

[package]
name="rest"
version = "0.0.2"
authors = ["[email protected]"]

[dependencies.rest_client]
git = "https://github.com/gtolle/rest_client"

some versions:

  • hyper: v0.9.4
  • rustc 1.9.0

Any hints to get this compiling?

Consider using a Builder pattern

It might be cool to have a Builder-style API for configuring requests:

let result = RestClient::builder("http://www.request-endpoint.com/")
    .param("hello", "world") // .params([("hello", "world"])
    .get(); //Fire off the request
GET /?hello=world HTTP/1.1

Then it can easily be extended with methods like .compressed(bool) to enable HTTP compression (suggesting that in a separate issue) and .header(Header) for custom headers.

.get(), .post(), etc. would complete the request and return a String with the body, wrapped in the proper Result type.

.get_json(), .post_json(), etc would complete the request and return the body decoded as JSON, wrapped in the proper Result type.

.get_reader(), .post_reader(), complete the request and return a Reader impl that wraps the client::Response type and reads the body. It would probably be an enum with compressed and uncompressed variants for HTTP compression.

.build() would build and return the client::Request object.

The existing RestClient methods can be adapted as wrappers for this pattern.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.