Learn SINATRA with Real Code Examples
Updated Nov 27, 2025
Explain
Sinatra provides a DSL for defining HTTP routes and their handlers in Ruby.
Ideal for small web applications, microservices, and APIs.
Supports multiple request types (GET, POST, PUT, DELETE) out of the box.
Integrates easily with Rack-compatible middleware and libraries.
Encourages convention over configuration for rapid development.
Core Features
Routing - map HTTP methods and paths to Ruby blocks
Middleware support - use Rack-compatible middleware
Request/Response objects - access headers, params, and body
Template rendering - embed Ruby in HTML views
Error handling and filters - before, after, and error blocks
Basic Concepts Overview
Route - defines an endpoint and HTTP method
Handler - block of code executed when route is matched
Request - object representing HTTP request data
Response - object representing HTTP response
Middleware - optional layer for processing requests/responses
Project Structure
app.rb - main Sinatra application file
config.ru - Rack configuration file
views/ - template files (ERB, Haml, Slim)
public/ - static assets
Gemfile - gem dependencies
Building Workflow
Define HTTP routes with corresponding handlers
Access query parameters and request body
Render templates for responses if needed
Use filters for pre/post-processing
Deploy app via Rack server or container
Difficulty Use Cases
Beginner: Single-file web app with GET/POST routes
Intermediate: Multi-route app with templates and static assets
Advanced: RESTful API with middleware and authentication
Expert: Modular Sinatra app with multiple files and helpers
Architect: Service-oriented microservices architecture using Sinatra
Comparisons
Sinatra vs Rails: Lightweight, minimal vs full-featured MVC
Sinatra vs Hanami: Minimal DSL vs structured framework
Sinatra vs Grape: General web apps vs API-focused DSL
Sinatra vs Roda: Simplicity vs performance and routing focus
Sinatra vs Padrino: Minimal vs feature-rich extension of Sinatra
Glossary
Route - maps HTTP request to handler
Handler - block executed for route
Middleware - pre/post-processing of requests/responses
Template - file for generating HTML
Rack - Ruby interface between web server and app