Yes, it's possible to set custom query parameters with HTTParty, which is a Ruby library used for making HTTP requests. HTTParty provides a simple way to make web requests and interact with APIs. When you want to add query parameters to a request, you can do so by including them in the options hash passed to HTTParty's HTTP method calls.
Here's an example of how you can set custom query parameters with HTTParty for a GET request:
require 'httparty'
# Define the base URI for the request
base_uri = 'https://api.example.com/data'
# Set custom query parameters
query_parameters = {
'param1' => 'value1',
'param2' => 'value2'
}
# Make a GET request with custom query parameters
response = HTTParty.get(base_uri, query: query_parameters)
# Print the response body
puts response.body
In the example above, query_parameters
is a hash that contains the custom query parameters you want to send with your GET request. The query:
key in the options hash tells HTTParty to append these parameters to the URL as a query string.
For a POST request, if you want to include parameters in the body of the request, you can use the body
key instead:
require 'httparty'
# Define the base URI for the request
base_uri = 'https://api.example.com/data'
# Set custom parameters for the POST request body
post_parameters = {
'param1' => 'value1',
'param2' => 'value2'
}
# Make a POST request with custom parameters in the body
response = HTTParty.post(base_uri, body: post_parameters)
# Print the response body
puts response.body
In this POST request example, post_parameters
is a hash that contains the parameters you want to include in the request body. By using the body:
key, you're instructing HTTParty to send these parameters as the request body.
Remember that when you're interacting with APIs, you should also handle other aspects of the request such as headers, authentication, and content type as required by the API you're working with. You can add these to the options hash as well, for example:
require 'httparty'
# Define the base URI for the request
base_uri = 'https://api.example.com/data'
# Set custom headers and query parameters
options = {
headers: { 'Authorization' => 'Bearer your_api_token', 'Content-Type' => 'application/json' },
query: { 'param1' => 'value1' }
}
# Make a GET request with headers and query parameters
response = HTTParty.get(base_uri, options)
# Print the response body
puts response.body
In this example, options
includes both custom headers and query parameters, showing how you can set multiple aspects of the HTTP request using HTTParty.