Skip to content

Instantly share code, notes, and snippets.

@midir99
Created February 12, 2026 21:54
Show Gist options
  • Select an option

  • Save midir99/cd691298ee4a80e83ed298fbb8435606 to your computer and use it in GitHub Desktop.

Select an option

Save midir99/cd691298ee4a80e83ed298fbb8435606 to your computer and use it in GitHub Desktop.
Consume JSON API with Ruby without 3rd party libraries
require 'json'
require 'net/http'
require 'uri'
# Calls a JSON API via GET request, if the response status code is successful the JSON response body is parsed and returned as a hash.
def http_get_json(url, headers={}, open_timeout: 5, read_timeout: 10)
uri = URI.parse(url)
http = Net::HTTP::new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")
http.open_timeout = open_timeout
http.read_timeout = read_timeout
request = Net::HTTP::Get.new(uri.request_uri)
request["Content-Type"] ||= "application/json"
request["Accept"] ||= "application/json"
headers.each do |key, value|
request[key] = value
end
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP #{response.code}: #{response.message}\n#{response.body}"
end
return JSON.parse(response.body)
end
# Calls a JSON API via POST request, if the response status code is successful the JSON response body is parsed and returned as a hash.
def http_post_json(url, payload = {}, headers = {}, open_timeout: 5, read_timeout: 10)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")
http.open_timeout = open_timeout
http.read_timeout = read_timeout
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] ||= "application/json"
request["Accept"] ||= "application/json"
headers.each do |key, value|
request[key] = value
end
request.body = JSON.generate(payload)
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP #{response.code}: #{response.message}\n#{response.body}"
end
return JSON.parse(response.body)
end
# Here's a sample:
response = http_get_json("https://pokeapi.co/api/v2/pokemon/pikachu")
puts response["name"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment