HTTParty Documentation

repository·main·Indexed 26 days ago

https://github.com/jnunemaker/httparty

A Ruby library for making HTTP requests. It provides simple class methods for quick tasks or a module to build structured API wrappers. Features include automatic JSON parsing, multipart file uploads with streaming support, SSL certificate configuration, and automatic decompression for gzip and deflate. Includes a CLI tool for querying web services from the terminal. Requires Ruby 2.7.0 or higher.

Tokens
5.4K
Snippets
10
Records
34
Agent score
91%

What's inside HTTParty

  1. Stream large file uploads

    main

    To reduce memory usage when uploading large files, enable streaming mode by setting stream_body: true. This allows HTTParty to stream the file in chunks instead of loading the entire file into memory.

    Note: If you encounter 400 errors, the server may not support streaming; try disabling this option.

    HTTParty.post('http://example.com/upload',
      body: {
        name: 'Foo Bar',
        avatar: File.open('/path/to/large_file.zip')
      },
      stream_body: true
    )
  2. Handle HTTP compression

    main

    HTTParty handles decompression automatically for gzip and deflate. For other encodings, you may need to install specific gems to enable automatic decompression:

    Content-EncodingRequired Gem
    br (Brotli)brotli
    compress (LZW)ruby-lzws
    zstd (Zstandard)zstd-ruby

    If you want to receive the raw, uncompressed byte string and handle decompression manually, use the skip_decompression: true option.

  3. Parse JSON responses

    main

    When the response Content-Type is application/json, HTTParty automatically parses the response into Ruby objects (hashes or arrays). By default, keys are returned as strings. To get keys as symbols, use the format: :plain option and manually parse the response using JSON.parse with symbolize_names: true.

    response = HTTParty.get('http://example.com', format: :plain)
    JSON.parse response, symbolize_names: true
  4. Handle authentication with Basic or Digest auth

    main

    HTTParty supports two primary authentication methods. You can provide them via the options hash or via the URI itself.

    Basic Auth via Options:

    options = { basic_auth: { username: 'user', password: 'password' } }

    Basic Auth via URI: If the URI contains user information (e.g., http://user:pass@example.com), HTTParty will automatically extract and use it for Basic Auth.

    Digest Auth via Options:

    options = { digest_auth: { username: 'user', password: 'password' } }

    Note: You cannot use both :basic_auth and :digest_auth at the same time.

  5. Implement a custom parser by subclassing HTTParty::Parser

    main

    You can customize how HTTParty parses response bodies by subclassing HTTParty::Parser. This allows you to intercept parsing for all formats or add support for new MIME types.

    Intercept all parsing

    Override the parse method to control the entire parsing lifecycle.

    Add a new format

    To add a new format (e.g., atom), merge the new MIME type into SupportedFormats and implement a corresponding method named after the format symbol.

    Restrict to specific formats

    You can override SupportedFormats to ensure your parser only handles specific MIME types.

    # Intercept the parsing for all formats
    class SimpleParser < HTTParty::Parser
      def parse
        perform_parsing
      end
    end
    
    # Add the atom format and parsing method to the default parser
    class AtomParsingIncluded < HTTParty::Parser
      SupportedFormats.merge!(
        {"application/atom+xml" => :atom}
      )
    
      def atom
        perform_atom_parsing
      end
    end
    
    # Only support the atom format
    class ParseOnlyAtom < HTTParty::Parser
      SupportedFormats = {"application/atom+xml" => :atom}
    
      def atom
        perform_atom_parsing
      end
    end
  6. Manage redirects and follow-up behavior

    main

    HTTParty automatically follows redirects by default. You can control this behavior using the following options:

    • Disable redirects: Set follow_redirects: false.
    • Limit redirect depth: Use the limit option to set the maximum number of hops.
    • Maintain HTTP method: By default, most redirects (like 301/302) will switch the method to GET. To preserve the original method (e.g., POST) during a redirect, use maintain_method_across_redirects: true and resend_on_redirect: true (note: these are used in conjunction with specific status codes like 307/308).
    • Cookie handling: HTTParty automatically captures Set-Cookie headers from redirect responses and includes them in subsequent requests in the redirect chain.
  7. Use HTTParty class methods for quick requests

    main

    You can perform HTTP requests immediately by calling class methods like .get directly on HTTParty. The response object provides access to the body, code, message, and headers.

    response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')
    
    puts response.body, response.code, response.message, response.headers.inspect
  8. Post JSON bodies

    main

    To send JSON data via POST, PUT, or PATCH requests, set the Content-Type header to application/json and provide a valid JSON string in the body. You can provide a raw string, use JSON.generate, or use .to_json on a Ruby object.

    # Using JSON.generate
    HTTParty.post('http://example.com', body: JSON.generate({ foo: 'bar' }), headers: { 'Content-Type' => 'application/json' })
    
    # Using object.to_json
    HTTParty.post('http://example.com', body: { foo: 'bar' }.to_json, headers: { 'Content-Type' => 'application/json' })
  9. Wrap HTTParty in a custom class

    main

    For better organization, you can include HTTParty in your own class. This allows you to define a base_uri and create instance methods that wrap specific API endpoints using self.class.get (or other HTTP methods).

    class StackExchange
      include HTTParty
      base_uri 'api.stackexchange.com'
    
      def initialize(service, page)
        @options = { query: { site: service, page: page } }
      end
    
      def questions
        self.class.get("/2.2/questions", @options)
      end
    
      def users
        self.class.get("/2.2/users", @options)
      end
    end
    
    stack_exchange = StackExchange.new("stackoverflow", 1)
    puts stack_exchange.questions
    puts stack_exchange.users