Skip to content

Ruby (Net::HTTP)

Net::HTTP idioms, persistent connections, and consuming the JSON response.

Ruby ships Net::HTTP in the standard library, which is enough to call any JSON API without adding a gem. For larger apps, HTTParty or Faraday can clean up the boilerplate. This guide focuses on Net::HTTP because it is always available, then shows the same calls in HTTParty for comparison.

Setup

Open one persistent connection if you are calling the API repeatedly. The Net::HTTP.start block keeps the TCP+TLS connection open for every call inside it, so a loop of 100 fetches becomes 100x cheaper.

require "net/http"
require "json"
require "uri"

API   = "https://gorest.co.in/public/v3"
TOKEN = ENV.fetch("GOREST_TOKEN")

BASE = URI(API)
HTTP = Net::HTTP.new(BASE.host, BASE.port)
HTTP.use_ssl = true
HTTP.start # open the TCP+TLS connection once and reuse it

Send the bearer token

Add the token to every request via a small helper. Nothing special; it just sets the same headers each time and parses the JSON response.

HEADERS = {
  "Authorization" => "Bearer #{TOKEN}",
  "Accept"        => "application/json",
  "Content-Type"  => "application/json"
}.freeze

def call(req)
  HEADERS.each { |k, v| req[k] = v }
  res = HTTP.request(req)
  [res.code.to_i, res.body && !res.body.empty? ? JSON.parse(res.body) : nil, res]
end

List users

# A list is { "data" => [...], "meta" => {...} }. Ids are UUID strings.
def list_users(status: "active", size: 25, after: nil)
  params = { "filter[status]" => status, "page[size]" => size }
  params["page[after]"] = after if after
  uri = URI("#{API}/users")
  uri.query = URI.encode_www_form(params)
  code, body, _ = call(Net::HTTP::Get.new(uri))
  raise "GET /users -> #{code}" unless code == 200
  body
end

list_users(status: "active")["data"].first(3)

Fetch a single user

def get_user(id)
  code, body, _ = call(Net::HTTP::Get.new(URI("#{API}/users/#{id}")))
  return nil if code == 404
  raise "GET /users/#{id} -> #{code}" unless code == 200
  body
end

Create, update, delete

Build the request, set body to the JSON payload, and let call handle the rest. A new user needs name and email; status is active unless you set it. Writes need a token with the users:write scope. PATCH changes only the fields you send, and there is no PUT in v3.

# Create
req = Net::HTTP::Post.new(URI("#{API}/users"))
req.body = JSON.dump(name: "Tenali Ramakrishna",
                     email: "tenali-#{Time.now.to_i}@example.com")
code, created, _ = call(req)
raise "Create failed: #{code}" unless code == 201

# Partial update
req = Net::HTTP::Patch.new(URI("#{API}/users/#{created['id']}"))
req.body = JSON.dump(status: "inactive")
call(req)

# Delete
call(Net::HTTP::Delete.new(URI("#{API}/users/#{created['id']}")))

A 422 means validation failed. The body is Problem Details, and its errors array holds { "pointer" => "...", "code" => "...", "detail" => "..." } hashes; pass them to your form layer:

req = Net::HTTP::Post.new(URI("#{API}/users"))
req.body = JSON.dump(name: "x")
code, problem, _ = call(req)

if code == 422
  problem["errors"].each { |e| puts "#{e['pointer']}: #{e['detail']}" }
end

Pagination

A list carries its paging state in meta, not in headers. meta["has_more"] says if another page exists, and meta["next_cursor"] is the value to send as page[after]. Loop until has_more is false:

def each_user(status: "active")
  return enum_for(:each_user, status: status) unless block_given?
  after = nil
  loop do
    page = list_users(status: status, size: 100, after: after)
    page["data"].each { |u| yield u }
    break unless page["meta"]["has_more"]
    after = page["meta"]["next_cursor"]
  end
end

each_user(status: "active").first(50).map { |u| u["email"] }

Retry on 429

The API rate-limits per access token. When you hit the limit, you get a 429 with a Retry-After header in seconds. Wrap requests in a small back-off helper:

def call_with_retry(req, attempts: 3)
  attempts.times do
    code, body, res = call(req)
    return [code, body, res] unless code == 429
    sleep [res["Retry-After"].to_i, 1].max
  end
  raise "Rate limited; gave up"
end

Same calls in HTTParty

If you prefer a higher-level client, HTTParty reduces every snippet above to one or two lines. It does the JSON parse and bearer header for you when you set the defaults on a class:

require "httparty"

class GoRest
  include HTTParty
  base_uri "https://gorest.co.in/public/v3"
  headers "Authorization" => "Bearer #{ENV.fetch('GOREST_TOKEN')}",
          "Content-Type"  => "application/json",
          "Accept"        => "application/json"

  def self.list_users(query = {})
    get("/users", query: query).parsed_response["data"]
  end

  def self.create_user(payload)
    post("/users", body: payload.to_json).parsed_response
  end
end

Tips

  • Reuse one Net::HTTP object across calls in the same process. Creating it again per call doubles your latency on every request.
  • Pass the token via env (GOREST_TOKEN). In Rails apps, expose it through the credentials file or Rails.application.config_for.
  • Time.now.to_i is a quick way to make test emails unique without a UUID dependency.
  • Tests for code that calls this API: stub with WebMock or VCR rather than hitting the network. Cassettes stay small if you ask for a small page[size].
Related guides

Keep going