HTTP Requests and APIs
Prerequisites: Working with JSON and YAML, Exceptions in depth
An API (Application Programming Interface) is a way for programs to talk to each other. Most web APIs work over HTTP: you send a request to a URL and get back a response — usually JSON.
Ruby's standard library includes net/http.
A GET request
require "net/http"
require "json"
uri = URI("https://api.github.com/repos/ruby/ruby")
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
repo = JSON.parse(response.body, symbolize_names: true)
puts "#{repo[:full_name]} has #{repo[:stargazers_count]} stars"
else
puts "Request failed: #{response.code} #{response.message}"
end
ruby/ruby has 22948 stars
(The number will be different when you run it.)
URI(...)parses the URL.get_responsereturns a response object withcode,body, and headers.- Always check the status before using the body.
Net::HTTPSuccesscovers every 2xx status.
A POST request with JSON, headers, and timeouts
require "net/http"
require "json"
uri = URI("https://httpbin.org/post")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true,
open_timeout: 5, read_timeout: 10) do |http|
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{ENV.fetch("API_TOKEN", "demo")}"
request.body = { title: "Hello" }.to_json
http.request(request)
end
puts response.code
200
Always set timeouts for network calls. Without them, a slow server can make your program hang for a long time.
Handling failures
Network code fails in ways ordinary code doesn't: no connection, DNS errors, timeouts. Rescue the specific errors:
begin
response = Net::HTTP.get_response(URI("https://example.invalid"))
rescue SocketError, Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNREFUSED => e
puts "Network problem: #{e.class}"
end
Many projects use a gem such as Faraday or HTTParty for a friendlier interface, but they're built on the same ideas.
Common mistakes
- Using the response body without checking the status code.
- Hard-coding API keys in source code. Read them from environment variables — the next lesson.
- No timeouts.