Last Updated: January 30, 2022
·
7.195K
· sativaware

Hello world! with Sinatra

Lets create a simple Sinatra Server that responds to /hello-world

First, create a folder for our example:

$ mkdir sinatra-hello-world
$ cd sinatra-hello-world

Next, create a Gemfile with the required Gems:

$ nano Gemfile
source "http://rubygems.org"

gem 'rake'

gem 'sinatra', require: 'sinatra'

Create a Sinatra server, with a simple /hello-world url:

$ nano server.rb
# Requires the Gemfile
require 'bundler' ; Bundler.require

# By default Sinatra will return the string as the response.
get '/hello-world' do
  "Hello World!"
end

Start the server from the terminal by executing the server.rb file with ruby.

$ ruby server.rb

INFO  WEBrick 1.3.1
INFO  ruby 1.9.3 (2012-04-20) [x86_64-darwin11.2.0]
== Sinatra/1.4.4 has taken the stage on 4567 for development with backup from WEBrick
INFO  WEBrick::HTTPServer#start: pid=3142 port=4567

By default, our Sinatra example will run at http://127.0.0.1:4567 using WEBbrick as the server.

Next, lets test the response using Curl - as expected the /hello-world url returns "Hello World!"

$ curl http://localhost:4567/hello-world
Hello World!%

Next, lets add a route that handles a JSON request for /hello-world - this sample is typical of an API which can be consumed by mobile devices or angular.js apps.

$ nano server.rb
require 'JSON'

get '/hello-world.json' do
  content_type :json # Content-Type: application/json;charset=utf-8

  # Use to_json to generate JSON based on the Ruby hash
  {greeting: 'Hello World!'}.to_json
end

Restart the server

Ctrl-C

$ ruby server.rb

Use Curl to test the new json URL(-v parameter shows HTTP headers and response)

$ curl -v http://localhost:4567/hello-world.json

> GET /hello-world.json HTTP/1.1
>
< HTTP/1.1 200 OK
< Content-Type: application/json;charset=utf-8

{"greeting":"Hello World!"}%

Read more about Sinatra

1 Response
Add your response

missing the command: "bundle install"

over 1 year ago ·