Back to Tutorials
Tips6/8/2025

Return JSON in Sinatra

apijsonsinatra

Returning JSON from a Sinatra endpoint is really easy. You just have to to the following :

require 'sinatra'
require 'json'

get '/hi' do
  # Specify the content type to return, json
  content_type :json
  { song: "Wake me Up" }.to_json
end

If you want to configure it for all your routes :

require 'sinatra'
require 'json'

before do
  content_type :json
end

get '/hi' do
  { song: "Wake me Up" }.to_json
end

Hope it helps ;)

Tibo

Comments

Loading comments...

Level Up Your Dev Skills & Income 💰💻

Learn how to sharpen your programming skills, monetize your expertise, and build a future-proof career — through freelancing, SaaS, digital products, or high-paying jobs.

Join 3,000+ developers learning how to earn more, improve their skills, and future-proof their careers.

Return JSON in Sinatra | Devmystify