### Basic HTTParty GET Request Source: https://github.com/jnunemaker/httparty/blob/main/README.md Use the class methods for quick HTTP requests. This example fetches questions from the Stack Exchange API and prints the response body, code, message, and headers. ```ruby # Use the class methods to get down to business quickly response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow') puts response.body, response.code, response.message, response.headers.inspect ``` -------------------------------- ### Install HTTParty Gem Source: https://github.com/jnunemaker/httparty/blob/main/website/index.html Install the HTTParty gem using the RubyGems package manager. This command requires administrator privileges. ```bash sudo gem install httparty ``` -------------------------------- ### Install HTTParty Gem Source: https://context7.com/jnunemaker/httparty/llms.txt Add the HTTParty gem to your project's Gemfile or install it directly using the gem command. ```ruby gem 'httparty' ``` ```ruby # gem install httparty ``` -------------------------------- ### Simple GET Request in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Performs a simple GET request and pretty-prints the Ruby object response. Useful for quick API checks. ```ruby httparty "https://api.stackexchange.com/2.2/questions?site=stackoverflow&pagesize=2" ``` -------------------------------- ### Post to Twitter API with Dynamic Authentication Source: https://github.com/jnunemaker/httparty/blob/main/website/index.html This example shows how to handle authentication dynamically by passing username and password during object initialization. It allows for more flexible authentication management compared to embedding credentials directly in the class. ```ruby class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {username: u, password: p} end def post(text) options = { query: {status: text}, basic_auth: @auth } self.class.post('/statuses/update.json', options) end end Twitter.new('username', 'password').post("It's an HTTParty and everyone is invited!") ``` -------------------------------- ### Install HTTParty Gem Source: https://github.com/jnunemaker/httparty/blob/main/README.md Install the HTTParty gem using the RubyGems package manager. Ensure you have Ruby 2.7.0 or higher installed. ```bash gem install httparty ``` -------------------------------- ### Verify HTTParty and SSL Configuration in Ruby Source: https://github.com/jnunemaker/httparty/wiki/Troubleshooting-on-Windows Run this script in a Ruby REPL to confirm that HTTParty is installed and that SSL certificates are being validated correctly. If an exception is raised, SSL is still misconfigured. ```ruby require 'httparty' puts "HTTParty Version: #{HTTParty::Version}" response = HTTParty.get('https://google.com') puts "Response Length: #{response.length}" ``` -------------------------------- ### GET Request with Basic Authentication in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Makes a GET request requiring basic authentication. Provide username and password for protected resources. ```ruby httparty -u alice:secret "https://httpbin.org/basic-auth/alice/secret" ``` -------------------------------- ### Perform GET Request with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Use `HTTParty.get` for simple GET requests. Query parameters are passed via the `:query` option. The response object provides access to status code, headers, and parsed body. Predicate methods like `ok?` and `success?` are available. ```ruby require 'httparty' # Simple GET — response is auto-parsed based on Content-Type response = HTTParty.get('https://api.stackexchange.com/2.2/questions', query: { site: 'stackoverflow', pagesize: 2 } ) puts response.code # => 200 puts response.message # => "OK" puts response.headers['content-type'] # => "application/json; charset=utf-8" # parsed_response is a Ruby Hash (auto-parsed from JSON) response.parsed_response['items'].each do |q| puts q['title'] end # Check status predicate methods puts response.ok? # => true puts response.not_found? # => false puts response.success? # => true ``` -------------------------------- ### HTTParty.put / HTTParty.patch / HTTParty.delete Source: https://context7.com/jnunemaker/httparty/llms.txt Performs PUT, PATCH, and DELETE requests with the same options interface as `get` and `post`. Also includes an example for `HEAD` requests. ```APIDOC ## HTTParty.put / HTTParty.patch / HTTParty.delete ### Description Performs PUT, PATCH, and DELETE requests with the same options interface as `get` and `post`. Also includes an example for `HEAD` requests. ### Method PUT, PATCH, DELETE, HEAD ### Endpoint [URL] ### Parameters #### Query Parameters - **id** (integer) - Optional - Used in DELETE requests to specify the resource ID. #### Request Body - **id** (integer) - Required (for PUT) - The ID of the resource to update. - **name** (string) - Required (for PUT/PATCH) - The name of the resource. ### Request Example ```ruby require 'httparty' # PUT — replace a resource response = HTTParty.put('https://httpbin.org/put', headers: { 'Content-Type' => 'application/json' }, body: { id: 42, name: 'Updated Name' }.to_json ) # PATCH — partial update response = HTTParty.patch('https://httpbin.org/patch', headers: { 'Content-Type' => 'application/json' }, body: { name: 'Patched Name' }.to_json ) # DELETE response = HTTParty.delete('https://httpbin.org/delete', query: { id: 42 } ) # HEAD — get headers only, no body response = HTTParty.head('https://httpbin.org/get') ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code. - **headers** (hash) - The response headers (for HEAD requests). - **parsed_response** (hash/object) - The parsed response body (for PUT, PATCH, DELETE). ``` -------------------------------- ### Verbose GET Request with JSON Output in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Performs a GET request with verbose output, showing both request and response headers, and formats the body as JSON. Useful for debugging. ```ruby httparty -v -f json "https://httpbin.org/get" ``` -------------------------------- ### GET Request with JSON Output in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Fetches data from a URL and formats the response as JSON. Use this when the API returns JSON. ```ruby httparty -f json "https://httpbin.org/json" ``` -------------------------------- ### Display HTTParty Version Source: https://context7.com/jnunemaker/httparty/llms.txt Shows the installed version of the HTTParty gem. Use this to check compatibility or report issues. ```ruby httparty --version ``` -------------------------------- ### Encapsulate API Calls in a Class Source: https://github.com/jnunemaker/httparty/blob/main/README.md Wrap HTTParty requests within a custom class to organize API interactions. This example defines a StackExchange class with methods for fetching questions and users. ```ruby # Or wrap things up in your own class 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 ``` -------------------------------- ### HTTParty.get — Perform a GET request Source: https://context7.com/jnunemaker/httparty/llms.txt Sends an HTTP GET request to the given URL. Returns an HTTParty::Response object that proxies the parsed response body, HTTP status code, headers, and the raw response. Query parameters can be passed as a hash via the :query option. ```APIDOC ## HTTParty.get — Perform a GET request ### Description Sends an HTTP GET request to the given URL. Returns an `HTTParty::Response` object that proxies the parsed response body, HTTP status code, headers, and the raw response. Query parameters can be passed as a hash via the `:query` option. ### Method GET ### Endpoint [URL] ### Parameters #### Query Parameters - **site** (string) - Required - The site to query. - **pagesize** (integer) - Optional - The number of items per page. ### Request Example ```ruby require 'httparty' response = HTTParty.get('https://api.stackexchange.com/2.2/questions', query: { site: 'stackoverflow', pagesize: 2 } ) ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code. - **message** (string) - The HTTP status message. - **headers** (hash) - The response headers. - **parsed_response** (hash/object) - The parsed response body (e.g., Hash for JSON). #### Response Example ```ruby puts response.code # => 200 puts response.message # => "OK" puts response.headers['content-type'] # => "application/json; charset=utf-8" response.parsed_response['items'].each do |q| puts q['title'] end ``` ``` -------------------------------- ### Post to Twitter API with Basic Authentication Source: https://github.com/jnunemaker/httparty/blob/main/website/index.html Example of wrapping the Twitter API to post updates using HTTParty. It demonstrates setting the base URI and basic authentication directly within the class. The response is automatically parsed as JSON. ```ruby class Twitter include HTTParty base_uri 'twitter.com' basic_auth 'username', 'password' end Twitter.post('/statuses/update.json', query: {status: "It's an HTTParty and everyone is invited!"}) ``` -------------------------------- ### Control Redirect Following Behavior Source: https://context7.com/jnunemaker/httparty/llms.txt Manage how HTTParty handles redirects using `no_follow`, `limit:`, and `maintain_method_across_redirects`. By default, up to 5 redirects are followed using GET. ```ruby require 'httparty' # Disable redirect following — access the redirect response directly begin HTTParty.get('https://httpbin.org/redirect/1', no_follow: true) rescue HTTParty::RedirectionTooDeep => e puts e.response.code # => 302 puts e.response['location'] end ``` ```ruby # Allow up to 3 redirects response = HTTParty.get('https://httpbin.org/redirect/2', limit: 3) puts response.code # => 200 ``` ```ruby # Keep POST method across a 302 redirect (instead of downgrading to GET) class PostClient include HTTParty base_uri 'https://api.example.com' maintain_method_across_redirects true end response = PostClient.post('/submit', body: { data: 'payload' } ) ``` -------------------------------- ### Perform PUT, PATCH, DELETE, and HEAD Requests Source: https://context7.com/jnunemaker/httparty/llms.txt HTTParty supports PUT, PATCH, DELETE, and HEAD requests using their respective methods. These methods share the same options interface as `get` and `post`. Use `HEAD` to retrieve only headers without a response body. ```ruby require 'httparty' # PUT — replace a resource response = HTTParty.put('https://httpbin.org/put', headers: { 'Content-Type' => 'application/json' }, body: { id: 42, name: 'Updated Name' }.to_json ) puts response.code # => 200 # PATCH — partial update response = HTTParty.patch('https://httpbin.org/patch', headers: { 'Content-Type' => 'application/json' }, body: { name: 'Patched Name' }.to_json ) puts response.code # => 200 # DELETE response = HTTParty.delete('https://httpbin.org/delete', query: { id: 42 } ) puts response.code # => 200 # HEAD — get headers only, no body response = HTTParty.head('https://httpbin.org/get') puts response.headers['content-type'] ``` -------------------------------- ### Parse JSON Response Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Automatically parses JSON responses into Ruby objects. Use `format: :plain` to get the raw response, then parse it manually with `JSON.parse` and `symbolize_names: true` for symbol keys. ```ruby response = HTTParty.get('http://example.com', format: :plain) JSON.parse response, symbolize_names: true ``` -------------------------------- ### Configure SSL with PEM Certificate Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Use the `pem` option to configure SSL client certificates. The `cert.pem` file should contain both the certificate and the private key. Provide a password if the key is protected. ```ruby class Client include HTTParty base_uri "https://example.com" pem File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), "123456" end ``` -------------------------------- ### Connection Adapter Source: https://context7.com/jnunemaker/httparty/llms.txt Replace the default `Net::HTTP` connection builder with custom logic for connection pooling, socket options, or instrumentation. ```APIDOC ## `connection_adapter` — Custom HTTP connection adapter Replaces the default `Net::HTTP` connection builder with your own logic — useful for connection pooling, custom socket options, or instrumentation. ```ruby require 'httparty' # Custom adapter that sets a local bind address class LocalBindAdapter < HTTParty::ConnectionAdapter def connection http = super http.local_host = options[:connection_adapter_options][:local_host] http end end class MyClient include HTTParty base_uri 'https://api.example.com' connection_adapter LocalBindAdapter, { local_host: '10.0.0.5' } end response = MyClient.get('/data') puts response.code # Proc-based adapter (inline) class CountingClient include HTTParty @@request_count = 0 connection_adapter(proc do |uri, options| @@request_count += 1 HTTParty::ConnectionAdapter.call(uri, options) end) def self.request_count @@request_count end end CountingClient.get('https://api.example.com/a') CountingClient.get('https://api.example.com/b') puts CountingClient.request_count # => 2 ``` ``` -------------------------------- ### Configure SSL with PKCS12 Certificate Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Use the `pkcs12` option to configure SSL client certificates when using a PKCS12 file. Provide the file content and the password for the certificate. ```ruby class Client include HTTParty base_uri "https://example.com" pkcs12 File.read("#{File.expand_path('.')}/path/to/certs/cert.p12"), "123456" end ``` -------------------------------- ### HTTParty Command Line Interface Source: https://github.com/jnunemaker/httparty/blob/main/README.md Use the `httparty` executable to query web services directly from the command line. By default, it outputs a pretty-printed Ruby object. Use `httparty --help` for all options. ```bash httparty "https://api.stackexchange.com/2.2/questions?site=stackoverflow" ``` -------------------------------- ### Configure SSL with CA File Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Specify a CA certificate file using `ssl_ca_file` to verify the server's SSL certificate. This is useful when the certificate is issued by a custom Certificate Authority. ```ruby class Client include HTTParty base_uri "https://example.com" ssl_ca_file "#{File.expand_path('.')}/path/to/certs/cert.pem" end ``` -------------------------------- ### URI Adapter Source: https://context7.com/jnunemaker/httparty/llms.txt Substitute the standard `URI` module with an object that responds to `.parse`, such as `Addressable::URI`, for enhanced URI handling. ```APIDOC ## `uri_adapter` — Custom URI adapter Replaces the standard `URI` module with any object that responds to `.parse`, such as `Addressable::URI`, which adds support for International Domain Names (IDN) and URI templates. ```ruby require 'httparty' require 'addressable' class IDNClient include HTTParty base_uri 'https://münchen.de' uri_adapter Addressable::URI end response = IDNClient.get('/news') puts response.code # Useful for URI templates response = HTTParty.get( 'https://api.example.com/users/{id}', uri_adapter: Addressable::URI ) ``` ``` -------------------------------- ### SSL/TLS Certificate Configuration with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Configure client certificate authentication using PEM or PKCS12 files, or set a custom CA file for server certificate verification. Server certificate validation can be skipped using `verify: false`. ```ruby require 'httparty' # PEM client certificate class MutualTLSClient include HTTParty base_uri 'https://secure.example.com' pem File.read('/path/to/client.pem'), 'optional_pem_password' end # PKCS12 client certificate class PKCS12Client include HTTParty base_uri 'https://secure.example.com' pkcs12 File.read('/path/to/client.p12'), 'p12_password' end # Custom CA file for server verification class CustomCAClient include HTTParty base_uri 'https://internal.example.com' ssl_ca_file '/etc/ssl/certs/internal-ca.crt' end # Skip server SSL verification (not recommended for production) response = HTTParty.get('https://self-signed.example.com/data', verify: false ) puts response.code ``` -------------------------------- ### Custom HTTP Connection Adapter Source: https://context7.com/jnunemaker/httparty/llms.txt Replace the default `Net::HTTP` connection builder with custom logic using `connection_adapter`. This is useful for connection pooling, custom socket options, or instrumentation. ```ruby require 'httparty' # Custom adapter that sets a local bind address class LocalBindAdapter < HTTParty::ConnectionAdapter def connection http = super http.local_host = options[:connection_adapter_options][:local_host] http end end class MyClient include HTTParty base_uri 'https://api.example.com' connection_adapter LocalBindAdapter, { local_host: '10.0.0.5' } end response = MyClient.get('/data') puts response.code # Proc-based adapter (inline) class CountingClient include HTTParty @@request_count = 0 connection_adapter(proc do |uri, options| @@request_count += 1 HTTParty::ConnectionAdapter.call(uri, options) end) def self.request_count @@request_count end end CountingClient.get('https://api.example.com/a') CountingClient.get('https://api.example.com/b') puts CountingClient.request_count # => 2 ``` -------------------------------- ### Configure SSL with CA Path Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Use `ssl_ca_path` to specify a directory containing CA certificates for SSL verification. HTTParty will look for certificates within this directory. ```ruby class Client include HTTParty base_uri "https://example.com" ssl_ca_path '/path/to/certs' end ``` -------------------------------- ### Custom URI Adapter with Addressable::URI Source: https://context7.com/jnunemaker/httparty/llms.txt Replace the standard `URI` module with `Addressable::URI` using `uri_adapter` to gain support for Internationalized Domain Names (IDN) and URI templates. ```ruby require 'httparty' require 'addressable' class IDNClient include HTTParty base_uri 'https://münchen.de' uri_adapter Addressable::URI end response = IDNClient.get('/news') puts response.code # Useful for URI templates response = HTTParty.get( 'https://api.example.com/users/{id}', uri_adapter: Addressable::URI ) ``` -------------------------------- ### Handling Unhandled Content-Encoding with Accept-Encoding: * Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md If Accept-Encoding is set to '*', and the server returns an unhandled Content-Encoding, you must manually decompress the response body. Parsed response will be nil in this case. ```ruby res = HTTParty.get('https://example.com/test.json', headers: { 'Accept-Encoding' => '*' }) encoding = res.headers['Content-Encoding'] if encoding JSON.parse(your_decompression_handling(res.body, encoding)) else # Content-Encoding not present implies decompressed JSON.parse(res.body) end ``` -------------------------------- ### Proxy Support with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Route all HTTP requests through a proxy server. Credentials for the proxy are optional. Per-request proxy settings can also be configured. ```ruby require 'httparty' class ProxiedClient include HTTParty base_uri 'https://api.example.com' http_proxy 'proxy.corporate.net', 8080, 'proxyuser', 'proxypass' end response = ProxiedClient.get('/data') puts response.code # Or per-request response = HTTParty.get('https://api.example.com/data', http_proxyaddr: 'proxy.corporate.net', http_proxyport: 8080 ) ``` -------------------------------- ### Debug Output Source: https://context7.com/jnunemaker/httparty/llms.txt Enable raw HTTP debug output by passing a stream to `Net::HTTP#set_debug_output`. Useful for debugging network-level issues. ```APIDOC ## `debug_output` — Raw HTTP debug output Passes a stream to `Net::HTTP#set_debug_output` to print the raw wire-level HTTP conversation. Useful for debugging SSL handshakes and unexpected request formats. ```ruby require 'httparty' # Print raw HTTP traffic to STDOUT response = HTTParty.get('https://httpbin.org/get', debug_output: STDOUT, headers: { 'User-Agent' => 'MyApp/1.0' } ) # opening connection to httpbin.org:443... # <- "GET /get HTTP/1.1\r\nUser-Agent: MyApp/1.0\r\n..." # -> "HTTP/1.1 200 OK\r\n..." # Class-level debug output to a log file class DebugClient include HTTParty base_uri 'https://api.example.com' debug_output File.open('http_debug.log', 'w') end ``` ``` -------------------------------- ### SSL Options within Call Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md SSL options like `pem` and `pem_password` can also be provided directly within the request call, overriding class-level configurations if necessary. ```ruby class Client include HTTParty base_uri "https://example.com" def self.fetch get("/resources", pem: File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), pem_password: "123456") end end ``` -------------------------------- ### Auto-Decompression with gzip/deflate Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md When Accept-Encoding includes gzip or deflate, Net::HTTP automatically decompresses the response. The Content-Encoding header will be omitted from the response if decompression is successful. ```ruby res = HTTParty.get('https://example.com/test.json', headers: { 'Accept-Encoding' => 'gzip,deflate,identity' }) JSON.parse(res.body) # safe ``` -------------------------------- ### Enable Raw HTTP Debug Output Source: https://context7.com/jnunemaker/httparty/llms.txt Use `debug_output` to pass a stream (like `STDOUT` or a file) to `Net::HTTP#set_debug_output` for raw HTTP conversation logging. This is useful for debugging SSL handshakes and request formats. ```ruby require 'httparty' # Print raw HTTP traffic to STDOUT response = HTTParty.get('https://httpbin.org/get', debug_output: STDOUT, headers: { 'User-Agent' => 'MyApp/1.0' } ) # opening connection to httpbin.org:443... # <- "GET /get HTTP/1.1\r\nUser-Agent: MyApp/1.0\r\n..." # -> "HTTP/1.1 200 OK\r\n..." # Class-level debug output to a log file class DebugClient include HTTParty base_uri 'https://api.example.com' debug_output File.open('http_debug.log', 'w') end ``` -------------------------------- ### Default Request Configuration with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Set default HTTP headers, query parameters, and cookies for all requests made by a class. Per-request options will override these defaults. ```ruby require 'httparty' class GitHubAPI include HTTParty base_uri 'https://api.github.com' headers 'Accept' => 'application/vnd.github.v3+json', 'Authorization' => "Bearer #{ENV['GITHUB_TOKEN']}", 'User-Agent' => 'MyApp/1.0' default_params per_page: 10 cookies session_id: 'abc123' def repos(username) self.class.get("/users/#{username}/repos") end end api = GitHubAPI.new response = api.repos('jnunemaker') response.each do |repo| puts "#{repo['name']} — ⭐ #{repo['stargazers_count']}" end ``` -------------------------------- ### Class-level Basic Auth with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Configure basic authentication at the class level for all requests. Ensure the base URI is set. ```ruby class SecureAPI include HTTParty base_uri 'https://api.example.com' basic_auth 'myuser', 'mypassword' end response = SecureAPI.get('/protected/resource') puts response.code # => 200 ``` -------------------------------- ### Configure Request/Response Logging with Ruby Logger Source: https://context7.com/jnunemaker/httparty/llms.txt Attach a Ruby Logger to log requests and responses. Supports built-in formats like :apache, :curl, and :logstash, or custom formatters. ```ruby require 'httparty' require 'logger' # Apache-style log to STDOUT HTTParty.get('https://httpbin.org/get', logger: Logger.new(STDOUT), log_level: :info, log_format: :apache ) # => I, [2024-01-15] INFO -- : GET https://httpbin.org/get 200 # Curl-style log — shows headers and body HTTParty.get('https://httpbin.org/get', logger: Logger.new(STDOUT), log_level: :debug, log_format: :curl ) ``` ```ruby # Class-level logging class MyAPI include HTTParty base_uri 'https://api.example.com' logger Logger.new('api.log'), :warn, :logstash end ``` ```ruby # Register a custom formatter class MyFormatter def initialize(logger, level) @logger = logger @level = level end def format(request, response) @logger.public_send(@level, "[#{Time.now}] #{request.http_method} -> #{response.code}" ) end end HTTParty::Logger.add_formatter(:my_format, MyFormatter) HTTParty.get('https://api.example.com/data', logger: Logger.new(STDOUT), log_format: :my_format ) ``` -------------------------------- ### Timeout Settings with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Configure connection, read, and write timeouts in seconds. `default_timeout` sets all three, while individual setters override it. Per-request timeouts can also be specified. ```ruby require 'httparty' class SlowAPI include HTTParty base_uri 'https://slow.example.com' open_timeout 3 # fail fast if can't connect read_timeout 30 # allow up to 30s for the response body write_timeout 10 # allow up to 10s to send request body end begin response = SlowAPI.get('/data') puts response.parsed_response rescue Net::OpenTimeout puts "Could not connect within 3 seconds" rescue Net::ReadTimeout puts "Server took too long to respond" end # Or per-request: response = HTTParty.get('https://slow.example.com/data', timeout: 5 # sets open, read, and write timeout to 5s ) ``` -------------------------------- ### Response Parsing Configuration with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Override default response format detection using `:format` or provide a custom parser class or `Proc`. This is useful for non-standard content types or specific parsing logic. ```ruby require 'httparty' # Force plain text (skip auto-parsing) response = HTTParty.get('https://example.com/data', format: :plain ) puts response.body # raw string # Custom parser subclass — add Atom support class AtomClient include HTTParty base_uri 'https://feeds.example.com' class AtomParser < HTTParty::Parser SupportedFormats.merge!('application/atom+xml' => :atom) protected def atom # use your preferred Atom library here body end end parser AtomParser end # Ad-hoc Proc parser — useful for testing or exotic formats class CustomClient include HTTParty parser(proc do |body, format| case format when :json then JSON.parse(body, symbolize_names: true) when :xml then MultiXml.parse(body) else body end end) end response = CustomClient.get('https://api.example.com/users') puts response[:name] # symbolized keys from JSON ``` -------------------------------- ### Mixin Pattern with `base_uri` and Defaults Source: https://context7.com/jnunemaker/httparty/llms.txt Include `HTTParty` in a class to set persistent configurations like `base_uri`, `default_params`, and `headers`. Subclasses inherit these defaults. Requests made via class methods use relative paths. ```ruby require 'httparty' class StackExchange include HTTParty base_uri 'https://api.stackexchange.com' default_params site: 'stackoverflow' headers 'Accept' => 'application/json' def initialize(page = 1) @options = { query: { page: page, pagesize: 5 } } end def questions self.class.get('/2.2/questions', @options) end def users self.class.get('/2.2/users', @options) end end api = StackExchange.new(1) response = api.questions response['items'].each do |q| puts "#{q['score']} — #{q['title']}" end # => 42 — How do I reverse a string in Ruby? # => 38 — What is the difference between a proc and a lambda? ``` -------------------------------- ### Skip SSL Verification Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Disable SSL certificate verification using `verify: false` or `verify_peer: false`. Use this cautiously when dealing with untrusted certificates or specific testing scenarios. ```ruby # Skips SSL certificate verification class Client include HTTParty base_uri "https://example.com" pem File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), "123456" def self.fetch get("/resources", verify: false) # You can also use something like: # get("resources", verify_peer: false) end end ``` -------------------------------- ### HTTParty::Response Object Methods Source: https://context7.com/jnunemaker/httparty/llms.txt Understand the `HTTParty::Response` object, which delegates to the parsed body and provides access to HTTP metadata like `code`, `headers`, `body`, and status predicate methods. ```ruby require 'httparty' response = HTTParty.get('https://httpbin.org/json') # HTTP metadata puts response.code # => 200 puts response.message # => "OK" puts response.http_version # => "1.1" puts response.headers['content-type'] # Status predicate methods (generated for every Net::HTTP status class) puts response.ok? # => true puts response.success? # => true (2xx) puts response.not_found? # => false # Parsed body — delegates automatically puts response['slideshow']['title'] # Hash access puts response.parsed_response.class # => Hash # Raw body string puts response.body # Marshal serialization — survives process boundaries serialized = Marshal.dump(response) deserialized = Marshal.load(serialized) puts deserialized.code # => 200 # Streaming: check fragment codes inside block HTTParty.get('https://httpbin.org/stream/3', stream_body: true) do |fragment| puts "chunk status: #{fragment.code}" end ``` -------------------------------- ### Per-request Basic Auth with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Apply basic authentication for a single HTTP request. This is useful for requests that require different credentials than the class-level default. ```ruby response = HTTParty.get('https://api.example.com/data', basic_auth: { username: 'myuser', password: 'mypassword' } ) ``` -------------------------------- ### include HTTParty — Mixin pattern with base_uri Source: https://context7.com/jnunemaker/httparty/llms.txt Including `HTTParty` in a class allows setting persistent defaults like `base_uri`, `default_params`, and `headers`. This pattern is useful for creating API clients with predefined configurations. ```APIDOC ## include HTTParty — Mixin pattern with `base_uri` ### Description Including `HTTParty` in a class lets you set persistent defaults. `base_uri` sets the host; instance or class methods call `get`, `post`, etc. with relative paths. All class-level defaults are inherited by subclasses. ### Usage ```ruby require 'httparty' class StackExchange include HTTParty base_uri 'https://api.stackexchange.com' default_params site: 'stackoverflow' headers 'Accept' => 'application/json' def initialize(page = 1) @options = { query: { page: page, pagesize: 5 } } end def questions self.class.get('/2.2/questions', @options) end def users self.class.get('/2.2/users', @options) end end api = StackExchange.new(1) response = api.questions response['items'].each do |q| puts "#{q['score']} — #{q['title']}" end ``` ### Configuration Options - **base_uri** (string) - Sets the base URL for all requests made by the class. - **default_params** (hash) - Sets default query parameters for all requests. - **headers** (hash) - Sets default headers for all requests. ``` -------------------------------- ### Stream Large File Downloads and Uploads Source: https://context7.com/jnunemaker/httparty/llms.txt Use `stream_body: true` to handle large files without buffering the entire content in memory. This is useful for both downloading and uploading large data. ```ruby require 'httparty' # Streaming download — write chunks directly to disk File.open('large_file.zip', 'wb') do |file| HTTParty.get('https://example.com/large_file.zip', stream_body: true) do |fragment| case fragment.code when 200 file.write(fragment) print '.' when 301, 302 # redirect fragment — don't write, HTTParty will follow else raise "Download failed with status #{fragment.code}" end end end puts "\nDownload complete" ``` ```ruby # Streaming upload — reduces memory usage for large files response = HTTParty.post('https://upload.example.com/files', body: { file: File.open('/path/to/large_video.mp4') }, stream_body: true ) puts response.code # => 201 ``` -------------------------------- ### HTTP Basic and Digest Authentication Source: https://context7.com/jnunemaker/httparty/llms.txt Configure HTTP Basic or Digest authentication credentials at the class level or on a per-request basis. Note that only one authentication type can be active at a time. ```ruby require 'httparty' ``` -------------------------------- ### HTTParty::Response Object Source: https://context7.com/jnunemaker/httparty/llms.txt Understand the `HTTParty::Response` object, which delegates to the parsed body and provides access to HTTP metadata and status predicate methods. ```APIDOC ## `HTTParty::Response` — Response object All request methods return an `HTTParty::Response` that transparently delegates to the parsed body (Hash, Array, etc.) while also exposing `code`, `headers`, `body`, and HTTP status predicate methods like `ok?`, `not_found?`, `success?`, etc. ```ruby require 'httparty' response = HTTParty.get('https://httpbin.org/json') # HTTP metadata puts response.code # => 200 puts response.message # => "OK" puts response.http_version # => "1.1" puts response.headers['content-type'] # Status predicate methods (generated for every Net::HTTP status class) puts response.ok? # => true puts response.success? # => true (2xx) puts response.not_found? # => false # Parsed body — delegates automatically puts response['slideshow']['title'] # Hash access puts response.parsed_response.class # => Hash # Raw body string puts response.body # Marshal serialization — survives process boundaries serialized = Marshal.dump(response) deserialized = Marshal.load(serialized) puts deserialized.code # => 200 # Streaming: check fragment codes inside block HTTParty.get('https://httpbin.org/stream/3', stream_body: true) do |fragment| puts "chunk status: #{fragment.code}" end ``` ``` -------------------------------- ### Third-Party Gem Decompression (Brotli, LZWS, Zstd) Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md For encodings like br, compress, or zstd, you must include the respective gems. HTTParty will automatically decompress if the required gem is present and decompression succeeds. Content-Encoding will be omitted from response headers. ```ruby require 'brotli' require 'lzws' require 'zstd-ruby' res = HTTParty.get('https://example.com/test.json', headers: { 'Accept-Encoding' => 'br,compress,zstd' }) JSON.parse(res.body) ``` -------------------------------- ### HTTParty.post — Perform a POST request Source: https://context7.com/jnunemaker/httparty/llms.txt Sends an HTTP POST request. Pass a body hash for form-encoded data, or a JSON string with the appropriate `Content-Type` header for JSON APIs. The `:query` option appends parameters to the URL instead of the body. ```APIDOC ## HTTParty.post — Perform a POST request ### Description Sends an HTTP POST request. Pass a body hash for form-encoded data, or a JSON string with the appropriate `Content-Type` header for JSON APIs. The `:query` option appends parameters to the URL instead of the body. ### Method POST ### Endpoint [URL] ### Parameters #### Query Parameters - **ref** (string) - Optional - Appended to the URL as a query string parameter. #### Request Body - **username** (string) - Required (for form-encoded) - The username. - **password** (string) - Required (for form-encoded) - The password. - **name** (string) - Required (for JSON) - The name. - **role** (string) - Required (for JSON) - The role. - **email** (string) - Required (for JSON) - The email address. ### Request Example ```ruby require 'httparty' require 'json' # Form-encoded POST response = HTTParty.post('https://httpbin.org/post', body: { username: 'alice', password: 's3cr3t' } ) # JSON POST response = HTTParty.post('https://httpbin.org/post', headers: { 'Content-Type' => 'application/json' }, body: { name: 'Alice', role: 'admin' }.to_json ) # POST with query string params appended to URL response = HTTParty.post('https://httpbin.org/post', query: { ref: 'homepage' }, body: { email: 'alice@example.com' } ) ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code. - **parsed_response** (hash/object) - The parsed response body, often containing details about the request made. ``` -------------------------------- ### HTTP Error Handling in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Configures HTTParty to exit with a non-zero status code on HTTP errors (400 or above). Useful for scripting and CI/CD pipelines. ```ruby httparty -r "https://httpbin.org/status/404" echo $? ``` -------------------------------- ### Query String Formatting Source: https://context7.com/jnunemaker/httparty/llms.txt Control how arrays are serialized in query strings. Supports default Rails bracket notation, flat notation, or a custom Proc for normalization. ```APIDOC ## `disable_rails_query_string_format` / `query_string_normalizer` — Query string formatting By default HTTParty serializes arrays in Rails bracket notation (`ids[]=1&ids[]=2`). Use `disable_rails_query_string_format` for flat notation, or supply a fully custom normalizer `Proc`. ```ruby require 'httparty' # Default Rails-style (bracket notation) response = HTTParty.get('https://api.example.com/items', query: { ids: [1, 2, 3] } ) # Request URL: /items?ids[]=1&ids[]=2&ids[]=3 # Flat notation (no brackets) class FlatAPI include HTTParty base_uri 'https://api.example.com' disable_rails_query_string_format end response = FlatAPI.get('/items', query: { ids: [1, 2, 3] }) # Request URL: /items?ids=1&ids=2&ids=3 # Custom query string normalizer (comma-separated values) class JSONAPIClient include HTTParty base_uri 'https://jsonapi.example.com' query_string_normalizer(proc do |query| query.map do |key, value| value.is_a?(Array) ? "#{key}=#{value.join(',')}" : "#{key}=#{value}" end.join('&') end) end response = JSONAPIClient.get('/resources', query: { filter: ['active', 'verified'] }) # Request URL: /resources?filter=active,verified ``` ``` -------------------------------- ### Configure Automatic Exception on Error Status Codes Source: https://context7.com/jnunemaker/httparty/llms.txt Use `raise_on` to automatically raise `HTTParty::ResponseError` for specified HTTP status codes. This can be configured at the class level or per request. ```ruby require 'httparty' class StrictAPI include HTTParty base_uri 'https://api.example.com' raise_on [404, 500, '5[0-9]{2}'] # also accepts regex strings end begin response = StrictAPI.get('/missing-resource') rescue HTTParty::ResponseError => e puts e.message # => "Code 404 - Not Found" puts e.response.code # => 404 puts e.response.body # => raw response body end ``` ```ruby # Or per-request begin HTTParty.get('https://api.example.com/error', raise_on: [500] ) rescue HTTParty::ResponseError => e puts "Server error: #{e.response.code}" end ``` -------------------------------- ### Perform POST Request with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Use `HTTParty.post` for POST requests. Form-encoded data is sent via the `body` hash. For JSON APIs, set the `Content-Type` header and pass a JSON string. Query parameters can be appended to the URL using the `:query` option. ```ruby require 'httparty' require 'json' # Form-encoded POST response = HTTParty.post('https://httpbin.org/post', body: { username: 'alice', password: 's3cr3t' } ) puts response.code # => 200 # JSON POST response = HTTParty.post('https://httpbin.org/post', headers: { 'Content-Type' => 'application/json' }, body: { name: 'Alice', role: 'admin' }.to_json ) puts response.parsed_response['json'] # => {"name"=>"Alice", "role"=>"admin"} # POST with query string params appended to URL response = HTTParty.post('https://httpbin.org/post', query: { ref: 'homepage' }, body: { email: 'alice@example.com' } ) ``` -------------------------------- ### Multipart File Upload Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Upload files using `multipart/form-data` encoding by including a `File` object in the request body. This is automatically handled by HTTParty when a `File` object is detected. ```ruby HTTParty.post('http://example.com/upload', body: { name: 'Foo Bar', avatar: File.open('/path/to/avatar.jpg') } ) ``` -------------------------------- ### Streaming Upload for Large Files Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Enable streaming mode for large file uploads to reduce memory usage by sending the file in chunks. Note that some servers may not support this feature, potentially causing errors. ```ruby HTTParty.post('http://example.com/upload', body: { name: 'Foo Bar', avatar: File.open('/path/to/large_file.zip') }, stream_body: true ) ``` -------------------------------- ### POST Request with JSON Body in Ruby Source: https://context7.com/jnunemaker/httparty/llms.txt Sends a POST request with a JSON payload and custom Content-Type header. Suitable for submitting data to an API. ```ruby httparty -a post -d '{"name":"Alice"}' -H "Content-Type:application/json" \ "https://httpbin.org/post" ``` -------------------------------- ### Perform Multipart File Uploads Source: https://context7.com/jnunemaker/httparty/llms.txt HTTParty automatically handles multipart/form-data encoding when a `File` object is present in the body hash. Use `multipart: true` to force this encoding. ```ruby require 'httparty' # Auto-detected multipart (File in body) response = HTTParty.post('https://api.example.com/upload', body: { name: 'Alice', email: 'alice@example.com', avatar: File.open('/path/to/avatar.jpg') } ) puts response.code # => 201 ``` ```ruby # Force multipart without a file response = HTTParty.post('https://api.example.com/form', multipart: true, body: { title: 'My Post', body: 'Content here' } ) puts response.code # => 200 ``` ```ruby # Streaming multipart upload for very large files response = HTTParty.post('https://api.example.com/videos', stream_body: true, body: { title: 'My Video', video: File.open('/path/to/large_video.mp4') } ) puts response.code ``` -------------------------------- ### Class-level Digest Auth with HTTParty Source: https://context7.com/jnunemaker/httparty/llms.txt Configure digest authentication at the class level. This method is more secure than basic authentication for certain scenarios. ```ruby class DigestClient include HTTParty base_uri 'https://api.example.com' digest_auth 'myuser', 'mypassword' end response = DigestClient.get('/digest-protected') puts response.code ``` -------------------------------- ### basic_auth / digest_auth — Authentication Source: https://context7.com/jnunemaker/httparty/llms.txt Sets HTTP Basic or Digest authentication credentials at the class level or per-request. Only one authentication type can be active at a time. ```APIDOC ## `basic_auth` / `digest_auth` — Authentication ### Description Sets HTTP Basic or Digest authentication credentials at the class level or per-request. Only one auth type may be active at a time. ### Usage ```ruby require 'httparty' # Example for basic_auth (digest_auth follows a similar pattern) class MyAPI include HTTParty basic_auth 'username', 'password' base_uri 'https://api.example.com' end # Or per-request: response = HTTParty.get('https://api.example.com/data', basic_auth: { username: 'user', password: 'pwd' }) ``` ### Parameters - **username** (string) - The username for authentication. - **password** (string) - The password for authentication. ### Authentication Types - **basic_auth**: For HTTP Basic Authentication. - **digest_auth**: For HTTP Digest Authentication. ``` -------------------------------- ### Disabling Automatic Decompression Source: https://github.com/jnunemaker/httparty/blob/main/docs/README.md Use the `skip_decompression: true` option to disable all automatic decompression. The response body will be raw, and you will receive the Content-Encoding header. ```ruby res = HTTParty.get('https://example.com/test.json', skip_decompression: true) encoding = res.headers['Content-Encoding'] JSON.parse(your_decompression_handling(res.body, encoding)) ```