Code Monkey home page Code Monkey logo

nestful's Introduction

Nestful is a simple Ruby HTTP/REST client with a sane API.

Installation

sudo gem install nestful

Features

  • Simple API
  • JSON requests
  • Resource API
  • Proxy support
  • SSL support

API

GET request

Nestful.get 'http://example.com' #=> "body"

POST request

# url-encoded form POST
Nestful.post 'http://example.com', :foo => 'bar'

# JSON POST
Nestful.post 'http://example.com', {:foo => 'bar'}, :format => :json

Parameters

# You can also provide nestled params
Nestful.get 'http://example.com', :nestled => {:vars => 1}

Request

Request is the base class for making HTTP requests - everthing else is just an abstraction upon it.

Nestful::Request.new(url, options).execute #=> <Nestful::Response>

Valid Request options are:

  • headers (hash)
  • params (hash)
  • method (:get/:post/:put/:delete/:head)
  • proxy
  • user
  • password
  • auth_type (:basic/:bearer)
  • timeout
  • ssl_options

Requests are run via the execute method.

Endpoint

The Endpoint class provides a single object to work with restful services. The following example does a GET request to the URL; http://example.com/assets/1/

Nestful::Endpoint.new('http://example.com')['assets'][1].get #=> Nestful::Response

Resource

If you're building a binding for a REST API, then you should consider using the Resource class.

class Charge < Nestful::Resource
  endpoint 'https://api.stripe.com/v1/charges'
  options :auth_type => :bearer, :password => 'sk_bar'

  def self.all
    self.new(get)
  end

  def self.find(id)
    self.new(get(id))
  end

  def refund
    post(:refund)
  end
end

Charge.all #=> []
Charge.find('ch_bar').amount

Response

All HTTP responses are in the form of a Nestful::Response instance. This contains the raw HTTP response, body, headers and a few helper methods:

response = Nestful.get('http://www.google.com')
response.body #=> '<html>...'
response.headers #=> {'Content-Type' => 'text/html'}
response.status #=> 200

You can also access the decoded body if available, such as for JSON responses:

response = Nestful.get('http://api.stripe.com/v1/charges')
charges  = response.decoded

All calls are proxied to the decoded body, so you can access JSON properties like this:

charges = Nestful.get('http://api.stripe.com/v1/charges')['data']

Credits

Parts of the connection code were inspired from ActiveResource.

nestful's People

Contributors

alex-stripe avatar brienw avatar bulkan avatar jasonbarnabe avatar knoopx avatar legolin avatar maccman avatar ominiom avatar sashazykov avatar warmwaffles avatar zlu 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestful's Issues

Unicode escape sequences cause partial body parse failure

noob dependency question

I am trying to run nestful under MacRuby (Ruby 1.9.2)

I have successfully installed the gems for
activesupport-3.0.0.rc2
and installed nestful-0.0.3

at runtime ( require 'nestful' ) the system is claiming a dependency on i18n
(even though there seems to be no reference to it)
I get a
"You don't have i18n installed in your application. Please add it to your Gemfile"
after installing i18n I get a
"incompatible character encodings: UTF-8 and ASCII-8BIT (Encoding::CompatibilityError)"

Im not sure if this error is because of nestful or because of activesupport
any clues would be most helpful
thx

NoMethodError: undefined method `strip' for nil:NilClass

     response = Nestful::Request.new("http://120.26.78.245:9089/payment/query.json",
                                      params: {
                                                  outer_trade_no: '111',
                                                  trade_type: 'INSTANT'
                                              },
                                      method: :get,
                                      headers: {"Version"=>"HTTP/1.0", "X-Forwarded-For"=>"122.224.209.110", "Host"=>"backend.test.souche.com", "Connection"=>"close", "Appname"=>"cheniu", "Appbuild"=>"IOS_23500", "Authorization"=>"Token token=53c5600a32f4be8c7af3603023b3d4ac", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate", "Accept-Language"=>"zh-Hans;q=1, en;q=0.9", "User-Agent"=>"cheniu/23500 (iPhone; iOS 8.3; Scale/2.00)", "Origin"=>nil}).execute

I think this request is legitimate,but it will raise a error:

NoMethodError: undefined method `strip' for nil:NilClass
from /Users/u2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/net/http/header.rb:17:in `block in initialize_http_header'

Changelog?

Hello, I'm wondering if there is or could be a changelog for the purposes of grokking what would result from upgrading this gem.

There isn't a TextFormat class

Tried using;

Nestful.post "http://localhost:8080/", :format =>:text, :params=>{:body => "some plain text"}

and recieved the following Exception;

uninitialized constant Nestful::Formats::TextFormat

I looked at the formats and there isn't a text/plain format. So I created one;

    module Nestful
      module Formats
        class TextFormat < Format
          def mime_type
            "text/plain"
          end

          def encode(body)
            body
          end

          def decode(body)
            body
          end
        end
      end
    end

and added the following to formats.rb

autoload :TextFormat, 'nestful/formats/text_format'

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can image, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Ruby 2.6.0 deprecation warning about error class

Error looks like:

[...]/nestful-1.1.3/lib/nestful/connection.rb:76: warning: constant Net::HTTPServerException is deprecated

If you have a preference re: solution here...

  • Remove it outright with understanding that older ruby versions might throw that error?
  • Make that list of errors conditional on which ruby version is being used?
  • Something else?

...I'd be happy to assist with PR.

Timeout issue only with web client on RAILS3

Hi,

I made a ruby client with Nestful gem and it works just fine running on my mac but when I ported the same code to a web client on RAILS3 timeout error pops up. With the ruby client, more than 1,000 requests are processed very fast without a hinch but with the web client, just single request hold up more than 60 secs resulting in timeout error.

Can you please help? Thanks,

the code for Nestful is like this:
response = Nestful.get 'http://localhost:3000/ad_impressions/new', :format => :json, :params =>{:app_id => app_id}

the error code looks like these:

Started POST "/web_clients/ad_request" for 127.0.0.1 at 2011-07-24 20:03:47 +0900
Processing by WebClientsController#ad_request as HTML
Parameters: {"_snowman"=>"�", "authenticity_token"=>"uZs0QZwR0/f2ecdEMVOrDFpQkQZrsmr81/Anu8g5+Tw=", "app_id"=>"10", "commit"=>"Show me the ad!"}
app_id : 10.
Completed in 59979ms

Nestful::TimeoutError (Timeout::Error):
app/controllers/web_clients_controller.rb:11:in `ad_request'

Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.3ms)
Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.5ms)
Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (9.0ms)

Started GET "/ad_impressions/new.json?params[app_id]=10" for 127.0.0.1 at 2011-07-24 20:04:47 +0900
Processing by AdImpressionsController#new as JSON
Parameters: {"params"=>{"app_id"=>"10"}}
Completed in 18ms

ActiveRecord::RecordNotFound (Couldn't find App without an ID):
app/controllers/ad_impressions_controller.rb:40:in `new'

Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.5ms)
Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.4ms)
Rendered /Users/dano/.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.0.rc/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (10.2ms)

Invalid request sent to Google Maps API

I'm playing with the Google Maps geolocation API, and can't get it to play nice with Nestful.

$ Nestful.get 'http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'
=> "{\n  \"status\": \"REQUEST_DENIED\",\n  \"results\": [ ]\n}\n"

but ...

$ curl 'http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'
>> { "status": "OK", "results": [ { ... _truncated_ ... } ] }

or

$ irb
>> require 'open-uri'
=> true
>> open('http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false')
=> #

Do I need to explicitly set some headers with Nestful to connect to these types of services? Or am I missing some other configuration? Thanks for any help,

Stu

Question: What are valid ssl options?

The README isn't very clear about this.
So what are the valid ssl options to add to the request?

More specifically: is there a way to define the SSL version?
Because I need a version that supports TLS1.2.

Multipart format

There used to be a multipart format that has been remove by this commit: 161eed5
Could you tell me what is the recommended way of sending files with the newer versions?
Thanks

JSON format automatically appends ".json" to your request

The .json isn't part of the standard and there are APIs out there that don't use it, for instance the Urban Airship API. For myself, I made a fork and hacked out the uri extending part but there's probably a nicer way to do it.

A

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.