Skip to content

What it is

Sinatra is a minimal Ruby web framework — routes are blocks, there is no imposed structure, and the whole application can be one file.

Routes are HTTP verb methods taking a path and a block. The return value becomes the response body.

Installation

gem install sinatra

Getting started

The smallest useful thing you can do with it, and what each part means.

A complete application
require 'sinatra'
require 'json'

set :port, 4567

get '/books/:id' do
  content_type :json
  book = STORE[params[:id]]
  halt 404, { error: 'not found' }.to_json unless book
  book.to_json
end

post '/books' do
  payload = JSON.parse(request.body.read)
  halt 422, { error: 'title required' }.to_json if payload['title'].to_s.empty?

  book = STORE.add(payload)
  status 201
  book.to_json
end

error JSON::ParserError do
  halt 400, { error: 'invalid JSON' }.to_json
end
halt stops processing immediately with the given status and body, which keeps guard clauses flat rather than nesting the happy path inside conditionals.

Advanced usage

Where the library earns its place over a simpler alternative.

Modular applications and middleware
# The modular style, for anything beyond a single file.
class BooksAPI < Sinatra::Base
  configure :production do
    set :show_exceptions, false   # never leak stack traces publicly
  end

  use Rack::Deflater

  before do
    content_type :json
    halt 401 unless authorised?(request.env['HTTP_AUTHORIZATION'])
  end

  helpers do
    def authorised?(header) = header == "Bearer #{ENV.fetch('API_TOKEN')}"
  end

  get('/books') { STORE.all.to_json }
end

# config.ru
run Rack::URLMap.new('/api' => BooksAPI)
show_exceptions must be off in production — the classic style leaves it on, which renders a full backtrace and source snippet to whoever triggered the error.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Routes return 404 unexpectedly
Sinatra matches routes in definition order. A broader pattern defined earlier will shadow a more specific one.
Stack traces appear in production responses
set :show_exceptions, false and set :environment, :production.

Best practices

  • Use the modular style (Sinatra::Base) for anything beyond a demonstration script.
  • Disable show_exceptions in production or you leak stack traces.
  • Use before filters for cross-cutting concerns rather than repeating checks per route.
  • Choose Sinatra for small services and Rails when you need an ORM, migrations and background jobs.

Background

Why it exists, and what it was reacting to.

Sinatra proved that a web framework could be a domain-specific language rather than a directory layout, and inspired Flask, Express and many others.