Skip to content

Instantly share code, notes, and snippets.

@col
Last active July 4, 2022 12:51
Show Gist options
  • Save col/37fe3c42c1c63dacaca7 to your computer and use it in GitHub Desktop.
Save col/37fe3c42c1c63dacaca7 to your computer and use it in GitHub Desktop.
Notes for creating a JSON API using Sinatra, SQL, DataMapper, Hal and hosted on Heroku.

Lightweight Ruby JSON API

Step 1 - Create a 'Hello World' Sinatra app

Create a Gemfile

source 'https://rubygems.org'

gem 'sinatra'
gem 'json'

Run

bundle install

Create a ruby file. ie) cocktail_api.rb

require 'sinatra'
require 'json'

get '/' do
  content_type :json  
  { message: 'Hello World' }.to_json
end

Run the app

ruby cocktail_api.rb

Step 2 - Add tests

Add RSpec to you Gemfile

group :test do
  gem 'rspec'
  gem 'rack-test'
end

Run

bundle install

Create a 'spec' directory and create two files: spec_helper.rb and cocktail_api.rb

spec_helper.rb

require 'sinatra'
require 'rspec'
require 'rack/test'

ENV['RACK_ENV'] = 'test'

cocktail_api_spec.rb

require 'spec_helper'
require_relative '../cocktail_api'

describe 'Cocktail API' do
	include Rack::Test::Methods

  	def app
    	Sinatra::Application.new
  	end

	describe 'root path' do 
		before do 
			get '/'
		end

		it 'should be successful' do
			expect(last_response).to be_ok
		end

		it 'should be a json response' do
			expect(last_response.content_type).to eq('application/json')
		end

		it 'should return a hello world message' do
			response_data = JSON.parse(last_response.body)
			expect(response_data['message']).to eq('Hello World')
		end	
	end
	
end

Run tests with

rspec

And/or create a Rakefile

require 'rspec/core/rake_task'
 
RSpec::Core::RakeTask.new :specs do |task|
  task.pattern = Dir['spec/**/*_spec.rb']
end
 
task :default => ['specs']

and run

rake

Step 3 - Deploy to Heroku

Create a config.ru file

require './app'
run Sinatra::Application

Then you can use rack to launch the app with

rackup

This will be required to deploy the app to Heroku.

If this is the first time you're using Heroku sign up for an account and then install the Heroku Toolkit from here:

https://devcenter.heroku.com/articles/getting-started-with-ruby#set-up

Once it's installed run

heroku login
heroku keys:add

Now Heroku is setup we can create an Heroku app for our project

heroku create
git push heroku master

Done! :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment