What are the supported HTTP methods in HTTParty?
HTTParty is a popular Ruby gem that simplifies HTTP requests by providing an intuitive interface for making API calls and web scraping. Understanding the supported HTTP methods is crucial for developers working with RESTful APIs, web services, and data extraction tasks.
Complete List of Supported HTTP Methods
HTTParty supports all standard HTTP methods defined in the HTTP specification:
1. GET Method
The GET method retrieves data from a server without modifying any resources.
require 'httparty'
# Basic GET request
response = HTTParty.get('https://api.example.com/users')
puts response.body
# GET with query parameters
response = HTTParty.get('https://api.example.com/users', {
query: {
page: 1,
limit: 10,
status: 'active'
}
})
2. POST Method
POST requests are used to create new resources or submit data to a server.
# POST request with JSON data
response = HTTParty.post('https://api.example.com/users', {
body: {
name: 'John Doe',
email: 'john@example.com',
role: 'developer'
}.to_json,
headers: {
'Content-Type' => 'application/json'
}
})
# POST with form data
response = HTTParty.post('https://api.example.com/login', {
body: {
username: 'user123',
password: 'secret123'
}
})
3. PUT Method
PUT requests are used to update existing resources or create resources with a specific identifier.
# Update user information
response = HTTParty.put('https://api.example.com/users/123', {
body: {
name: 'Jane Doe',
email: 'jane@example.com',
status: 'inactive'
}.to_json,
headers: {
'Content-Type' => 'application/json',
'Authorization' => 'Bearer your-token-here'
}
})
4. PATCH Method
PATCH requests are used for partial updates to existing resources.
# Partial update of user profile
response = HTTParty.patch('https://api.example.com/users/123', {
body: {
status: 'active'
}.to_json,
headers: {
'Content-Type' => 'application/json'
}
})
5. DELETE Method
DELETE requests are used to remove resources from the server.
# Delete a user
response = HTTParty.delete('https://api.example.com/users/123', {
headers: {
'Authorization' => 'Bearer your-token-here'
}
})
# Check if deletion was successful
puts "User deleted successfully" if response.code == 204
6. HEAD Method
HEAD requests retrieve only the headers of a response without the body content, useful for checking resource metadata.
# Check if a resource exists
response = HTTParty.head('https://api.example.com/users/123')
puts "Resource exists" if response.code == 200
puts "Content-Type: #{response.headers['content-type']}"
puts "Last-Modified: #{response.headers['last-modified']}"
7. OPTIONS Method
OPTIONS requests are used to determine which HTTP methods are supported by a server endpoint.
# Check supported methods for an endpoint
response = HTTParty.options('https://api.example.com/users')
allowed_methods = response.headers['allow']
puts "Supported methods: #{allowed_methods}"
Class-Level vs Instance-Level Usage
HTTParty provides two ways to use these HTTP methods:
Class-Level Methods (Simple Usage)
# Direct class method calls
response = HTTParty.get('https://api.example.com/data')
response = HTTParty.post('https://api.example.com/data', body: data)
response = HTTParty.put('https://api.example.com/data/1', body: data)
response = HTTParty.patch('https://api.example.com/data/1', body: partial_data)
response = HTTParty.delete('https://api.example.com/data/1')
Instance-Level Methods (Class Integration)
class ApiClient
include HTTParty
base_uri 'https://api.example.com'
def fetch_users
self.class.get('/users')
end
def create_user(user_data)
self.class.post('/users', {
body: user_data.to_json,
headers: { 'Content-Type' => 'application/json' }
})
end
def update_user(id, user_data)
self.class.put("/users/#{id}", {
body: user_data.to_json,
headers: { 'Content-Type' => 'application/json' }
})
end
end
Advanced HTTP Method Usage
Custom HTTP Methods
HTTParty also supports custom HTTP methods using the generic request
method:
# Using custom HTTP method
response = HTTParty.send(:request, :copy, 'https://api.example.com/resource', {
headers: {
'Destination' => '/new-location'
}
})
Handling Response Codes
Different HTTP methods typically return different status codes:
response = HTTParty.post('https://api.example.com/users', body: user_data)
case response.code
when 200
puts "Success: #{response.parsed_response}"
when 201
puts "Created: #{response.parsed_response}"
when 400
puts "Bad Request: #{response.parsed_response['error']}"
when 401
puts "Unauthorized: Check your credentials"
when 404
puts "Not Found: Resource doesn't exist"
when 500
puts "Server Error: #{response.parsed_response}"
end
Best Practices for HTTP Methods
1. Use Appropriate Methods
- GET: For data retrieval and read operations
- POST: For creating new resources
- PUT: For complete resource updates
- PATCH: For partial resource updates
- DELETE: For resource removal
- HEAD: For metadata checks
- OPTIONS: For capability discovery
2. Handle Errors Gracefully
begin
response = HTTParty.get('https://api.example.com/data')
if response.success?
data = response.parsed_response
else
puts "Request failed with code: #{response.code}"
end
rescue HTTParty::Error => e
puts "HTTParty error: #{e.message}"
rescue StandardError => e
puts "General error: #{e.message}"
end
3. Set Appropriate Headers
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'User-Agent' => 'MyApp/1.0',
'Authorization' => 'Bearer token123'
}
response = HTTParty.post('https://api.example.com/data', {
body: data.to_json,
headers: headers
})
Common Use Cases by Method
API Integration
class WeatherAPI
include HTTParty
base_uri 'https://api.weather.com/v1'
def current_weather(city)
self.class.get("/current", query: { city: city, key: api_key })
end
def update_location(location_data)
self.class.put("/locations/#{location_data[:id]}", {
body: location_data.to_json,
headers: { 'Content-Type' => 'application/json' }
})
end
end
Web Scraping with Form Submission
# Login form submission
login_response = HTTParty.post('https://example.com/login', {
body: {
username: 'user',
password: 'pass'
}
})
# Extract data after authentication
if login_response.code == 200
data_response = HTTParty.get('https://example.com/protected-data', {
headers: {
'Cookie' => login_response.headers['set-cookie']
}
})
end
Conclusion
HTTParty supports all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) and provides flexible ways to use them through both class-level and instance-level approaches. Understanding when and how to use each method is essential for effective API integration and web scraping tasks. The library's intuitive interface makes it easy to work with RESTful services while maintaining clean, readable code.
For more advanced web scraping scenarios that require JavaScript execution, consider exploring how to handle dynamic content that loads after page load or learn about monitoring network requests for comprehensive data extraction strategies.