HTTP (Hypertext Transfer Protocol) is fundamental to web communication. Ruby provides robust tools for working with HTTP, enabling developers to create powerful web applications and interact with web services effortlessly.
Ruby offers several ways to make HTTP requests. The built-in Net::HTTP
library is a common choice for basic operations.
require 'net/http'
require 'uri'
uri = URI('https://api.example.com/data')
response = Net::HTTP.get(uri)
puts response
This simple example demonstrates how to make a GET request and print the response body.
When working with HTTP responses, it's crucial to check status codes and parse the response body appropriately.
uri = URI('https://api.example.com/data')
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
puts data
else
puts "Request failed with status: #{response.code}"
end
This code snippet shows how to handle different response scenarios and parse JSON data.
While Net::HTTP
is powerful, many Ruby developers prefer third-party libraries for their simplicity and additional features:
Ruby's HTTP capabilities make it ideal for interacting with web APIs. Here's an example using the HTTParty gem:
require 'httparty'
response = HTTParty.get('https://api.github.com/users/octocat')
if response.success?
user = response.parsed_response
puts "Username: #{user['login']}"
puts "Followers: #{user['followers']}"
else
puts "Failed to fetch data: #{response.code}"
end
This example demonstrates how to make a GET request to the GitHub API and process the JSON response.
To further enhance your Ruby web development skills, explore these related topics:
By mastering Ruby's HTTP capabilities, you'll be well-equipped to build robust web applications and integrate with various web services efficiently.