REST APIs

suggest change

A REST API exposes resources (books, users, orders) at URLs and lets clients act on them with standard HTTP methods. Requests and responses usually carry JSON.

Method URL Meaning Typical success status
GET /books list books 200 OK
GET /books/42 get one book 200 OK
POST /books create a book 201 Created + Location header
PATCH /books/42 update some fields 200 OK
PUT /books/42 replace the book 200 OK
DELETE /books/42 delete the book 204 No Content

Errors are reported with status codes too: 400 (malformed request), 401 / 403 (not authenticated / not allowed), 404 (no such resource), 422 (valid JSON but invalid data), 429 (rate limited), 5xx (server failure).

This article shows both sides: calling a REST API from Ruby and building a small one with Sinatra. For details on headers see the HTTP headers article; for JSON itself see the JSON chapter.

Calling a REST API with Net::HTTP

Net::HTTP ships with Ruby, so it needs no gems. A one-off GET is short:

require 'net/http'
require 'json'

res = Net::HTTP.get_response(URI('https://api.github.com/repos/ruby/ruby'),
                             { 'Accept' => 'application/json' })
raise "HTTP #{res.code}" unless res.is_a?(Net::HTTPSuccess)

repo = JSON.parse(res.body)
puts "#{repo['full_name']}: #{repo['stargazers_count']} stars"

Real code needs more: timeouts, authentication, JSON request bodies, errors mapped to exceptions, retries and pagination. It pays to wrap all of that in a small client class:

require 'net/http'
require 'json'

class ApiClient
  class Error < StandardError
    attr_reader :response # Net::HTTPResponse or nil

    def initialize(message, response = nil)
      super(message)
      @response = response
    end

    def status = response&.code&.to_i
    def body = response&.body
  end
  class NetworkError < Error; end   # timeout, connection refused, DNS, TLS
  class ClientError < Error; end    # 4xx: our fault, don't retry
  class NotFound < ClientError; end # 404
  class ServerError < Error; end    # 5xx: their fault, may retry
  class RateLimited < ClientError   # 429: slow down, then retry
    def retry_after = response['Retry-After'].to_i.clamp(1, 60)
  end

  MAX_ATTEMPTS = 3
  RETRYABLE_METHODS = %w[GET HEAD PUT DELETE OPTIONS].freeze # idempotent

  def initialize(base_url, token: nil)
    @base = URI(base_url)
    @token = token
  end

  def get(path, query = {}) = parse(request(Net::HTTP::Get, path, query: query))
  def post(path, data)      = parse(request(Net::HTTP::Post, path, body: data))
  def patch(path, data)     = parse(request(Net::HTTP::Patch, path, body: data))
  def delete(path)          = parse(request(Net::HTTP::Delete, path))

  # Yields items from all pages, following `Link: <url>; rel="next"` headers.
  def each_item(path, query = {})
    return enum_for(:each_item, path, query) unless block_given?

    res = request(Net::HTTP::Get, path, query: query)
    loop do
      parse(res).each { yield _1 }
      next_url = next_link(res['Link']) or break
      res = request(Net::HTTP::Get, next_url)
    end
  end

  private

  def request(method_class, path, query: {}, body: nil)
    uri = @base + path # relative path ("books/1") or absolute URL
    uri.query = URI.encode_www_form(query) unless query.empty?

    req = method_class.new(uri)
    req['Accept'] = 'application/json'
    req['Authorization'] = "Bearer #{@token}" if @token
    if body
      req['Content-Type'] = 'application/json'
      req.body = JSON.generate(body)
    end

    attempts = 0
    begin
      attempts += 1
      check_status(perform(uri, req))
    rescue NetworkError, ServerError, RateLimited => e
      raise if attempts >= MAX_ATTEMPTS || !RETRYABLE_METHODS.include?(req.method)
      sleep(e.is_a?(RateLimited) ? e.retry_after : 2**attempts)
      retry
    end
  end

  def perform(uri, req)
    Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
                    open_timeout: 5, read_timeout: 15, write_timeout: 15) do |http|
      http.request(req)
    end
  rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout,
         SocketError, SystemCallError, OpenSSL::SSL::SSLError => e
    raise NetworkError, "#{req.method} #{uri}: #{e.class}: #{e.message}"
  end

  def check_status(res)
    return res if res.is_a?(Net::HTTPSuccess)

    error_class = case res.code.to_i
                  when 404 then NotFound
                  when 429 then RateLimited
                  when 400..499 then ClientError
                  when 500..599 then ServerError
                  else Error # e.g. 3xx: Net::HTTP does not follow redirects
                  end
    raise error_class.new("#{res.code} #{res.message}", res)
  end

  def parse(res)
    return nil if res.body.nil? || res.body.empty? # e.g. 204 No Content
    JSON.parse(res.body)
  end

  def next_link(header)
    header.to_s.split(',').each do |part|
      url, *params = part.split(';').map(&:strip)
      return url.delete_prefix('<').delete_suffix('>') if params.include?('rel="next"')
    end
    nil
  end
end

Points worth noticing:

Using the client against the server built later in this article:

api = ApiClient.new('http://localhost:4567/', token: ENV['API_TOKEN'])

book = api.post('books', { title: 'Neuromancer', author: 'William Gibson', year: 1984 })
# => {"title" => "Neuromancer", "author" => "William Gibson", "year" => 1984, "id" => 1}

api.patch("books/#{book['id']}", { year: 1985 })
api.each_item('books', per_page: 50).map { _1['title'] }
api.delete("books/#{book['id']}") # => nil (204 No Content)

begin
  api.get("books/#{book['id']}")
rescue ApiClient::NotFound => e
  puts "#{e.message}: #{e.body}" # => 404 Not Found: {"error":"book 1 not found"}
rescue ApiClient::Error => e
  warn "API call failed: #{e.message}"
end

Note that @base + path follows URL resolution rules: with a base of https://api.example.com/v1/ use relative paths like 'books'; a leading slash ('/books') would drop the /v1 part.

Faraday and HTTParty

For larger projects a gem saves boilerplate. Faraday (gem install faraday) builds a connection from middleware; JSON encoding/decoding, auth and raising on errors are built in:

require 'faraday'

conn = Faraday.new(url: 'http://localhost:4567', request: { open_timeout: 5, timeout: 15 }) do |f|
  f.request :authorization, 'Bearer', ENV.fetch('API_TOKEN')
  f.request :json         # encode request bodies as JSON
  f.response :raise_error # raise Faraday::Error subclasses on 4xx/5xx
  f.response :json        # parse JSON responses into Hashes
end

res = conn.post('/books', { title: 'Hyperion', author: 'Dan Simmons' })
res.status              # => 201
res.headers['location'] # => "http://localhost:4567/books/2"
res.body                # => {"title" => "Hyperion", "author" => "Dan Simmons", "id" => 2}

begin
  conn.get('/books/999')
rescue Faraday::ResourceNotFound => e
  e.response[:status] # => 404
  e.response[:body]   # => {"error" => "book 999 not found"}
end

Middleware runs in reverse order for responses, so registering :raise_error before :json means the error's body is already parsed. Retries are available via the faraday-retry gem (f.request :retry).

HTTParty (gem install httparty) is popular for quick API wrappers. Including it in a class gives class-level defaults:

require 'httparty'
require 'json'

class BooksApi
  include HTTParty
  base_uri 'http://localhost:4567'
  headers 'Accept' => 'application/json', 'Authorization' => "Bearer #{ENV.fetch('API_TOKEN')}"
  default_timeout 10
  format :json
end

res = BooksApi.post('/books', body: JSON.generate(title: 'Solaris', author: 'Stanislaw Lem'),
                              headers: { 'Content-Type' => 'application/json' })
res.code            # => 201
res.parsed_response # => {"title" => "Solaris", "author" => "Stanislaw Lem", "id" => 3}

res = BooksApi.get('/books/999')
res.success?        # => false (HTTParty doesn't raise on 4xx/5xx)
res['error']        # => "book 999 not found"

Building a JSON REST API with Sinatra

Sinatra (gem install sinatra rackup puma) maps HTTP methods and paths to blocks, which fits REST naturally. The API below manages books with full CRUD, validation, proper status codes and pagination:

# app.rb
require 'sinatra'
require 'json'

# In-memory, thread-safe storage. Use a database in a real app.
class BookStore
  def initialize
    @books = {}
    @next_id = 0
    @lock = Mutex.new
  end

  def all = @lock.synchronize { @books.values }
  def find(id) = @lock.synchronize { @books[id] }
  def delete(id) = @lock.synchronize { @books.delete(id) }

  def create(attrs)
    @lock.synchronize do
      id = @next_id += 1
      @books[id] = attrs.merge('id' => id)
    end
  end

  def update(id, attrs)
    @lock.synchronize { @books[id]&.merge!(attrs) }
  end
end

STORE = BookStore.new

helpers do
  def json(data, status_code = 200)
    halt status_code, JSON.generate(data)
  end

  def json_body
    data = JSON.parse(request.body.read)
    data.is_a?(Hash) ? data : json({ error: 'expected a JSON object' }, 400)
  rescue JSON::ParserError
    json({ error: 'invalid JSON' }, 400)
  end

  # Returns only permitted attributes or halts with 422.
  def validate(attrs, partial: false)
    errors = {}
    %w[title author].each do |field|
      next if partial && !attrs.key?(field)
      v = attrs[field]
      errors[field] = 'must be a non-empty string' unless v.is_a?(String) && !v.strip.empty?
    end
    if attrs.key?('year') && !attrs['year'].is_a?(Integer)
      errors['year'] = 'must be an integer'
    end
    json({ error: 'validation failed', details: errors }, 422) unless errors.empty?
    attrs.slice('title', 'author', 'year')
  end

  def find_book!(id)
    STORE.find(Integer(id, exception: false)) || json({ error: "book #{id} not found" }, 404)
  end
end

before { content_type :json }

# GET /books?page=2&per_page=10
get '/books' do
  page     = [params.fetch('page', 1).to_i, 1].max
  per_page = params.fetch('per_page', 20).to_i.clamp(1, 100)
  books    = STORE.all.sort_by { _1['id'] }
  items    = books.slice((page - 1) * per_page, per_page) || []

  if page * per_page < books.size
    headers 'link' => %(<#{url("/books?page=#{page + 1}&per_page=#{per_page}")}>; rel="next")
  end
  JSON.generate(items)
end

get '/books/:id' do
  JSON.generate(find_book!(params['id']))
end

post '/books' do
  book = STORE.create(validate(json_body))
  status 201
  headers 'location' => url("/books/#{book['id']}")
  JSON.generate(book)
end

patch '/books/:id' do
  book = find_book!(params['id'])
  JSON.generate(STORE.update(book['id'], validate(json_body, partial: true)))
end

delete '/books/:id' do
  book = find_book!(params['id'])
  STORE.delete(book['id'])
  204 # no body
end

not_found do
  # replace Sinatra's HTML page for unknown routes, keep JSON errors from find_book!
  JSON.generate(error: 'not found') if response.body.empty?
end

error do
  JSON.generate(error: 'internal server error') # don't leak exception details
end

Run it with ruby app.rb and try it with curl:

$ curl -i -X POST localhost:4567/books -H 'content-type: application/json' \
       -d '{"title":"Dune","author":"Frank Herbert","year":1965}'
HTTP/1.1 201 Created
content-type: application/json
location: http://localhost:4567/books/1
x-content-type-options: nosniff
content-length: 60

{"title":"Dune","author":"Frank Herbert","year":1965,"id":1}

$ curl -s -X POST localhost:4567/books -H 'content-type: application/json' \
       -d '{"title":"","year":"old"}'
{"error":"validation failed","details":{"title":"must be a non-empty string","author":"must be a non-empty string","year":"must be an integer"}}

How the pieces map to REST conventions:

The same design works in a bare Rack app, Roda or Hanami. In Rails, use rails new myapi --api and resources :books in config/routes.rb to get the same seven routes, with render json: book, status: :created in controllers.

Testing the API

rack-test (gem install rack-test) calls the app in-process, without starting a server:

# test_app.rb
ENV['APP_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'
require_relative 'app'

class BooksApiTest < Minitest::Test
  include Rack::Test::Methods

  def app = Sinatra::Application

  def test_create_and_fetch
    post '/books', JSON.generate(title: 'Dune', author: 'Frank Herbert'),
         'CONTENT_TYPE' => 'application/json'
    assert_equal 201, last_response.status
    id = JSON.parse(last_response.body)['id']

    get "/books/#{id}"
    assert_equal 'Dune', JSON.parse(last_response.body)['title']
  end

  def test_validation_error
    post '/books', JSON.generate(title: ''), 'CONTENT_TYPE' => 'application/json'
    assert_equal 422, last_response.status
  end

  def test_missing_book
    get '/books/9999'
    assert_equal 404, last_response.status
  end
end

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents