Setting up a Ruby(Sinatra) and MongoDB Based App Server

Nagesh Bansal
5 min readJan 22, 2020

Before we talk about how, let us talk about why. Why do we need an App Server? An app server is a layer that acts as an intermediary between the users and the actual data while incorporating the organization's business logic. An app server provides an interface, called Application Programming Interface or API which is a contract, for two applications to communicate and exchange data. In other words, an API is a messenger that delivers your request to the provider that you’re requesting it from and then delivers the response back to you.

With newer developments, it is possible for the user(the frontend) to directly communicate with the database directly. However, if a complex logic has to be integrated into an application, which is true in most cases, then you definitely need an app server. Besides, with the growing usage of mobile, if you are keen on delivering a truly mobile-first experience and avoid clunky non-responsive websites, an app server is your friend.

Since learning how to create web APIs is becoming so fundamental, that’s what we are going to do today. Let’s look at a simple Ruby API.

There are a wide variety of Ruby frameworks available. The most popularly known is Ruby on Rails. These days, the other frameworks are starting to grow in popularity too due to their diversity and functionalities. We will mainly discuss three available frameworks, i.e., Rails, Sinatra and Padrino.

What is Rails? Web development that doesn’t hurt. Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.

What is Sinatra? Classy web-development dressed in a Domain Specific Language(DSL). Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort. Sinatra aims to be small and flexible. It doesn’t follow the typical MVC patterns used in other Ruby frameworks. A route in Sinatra is a pair composed of an HTTP method and a pattern. The pattern is used to match URLs to blocks.

What is Padrino? A powerful full-featured ruby framework built on top of the Sinatra. Padrino is a ruby framework built upon the excellent Sinatra Microframework. Padrino was created to make it fun and easy to code more advanced web applications while still adhering to the spirit that makes Sinatra great!. It strives to be as small, fast, and lightweight as possible.

Today, we will work with Sinatra as our Ruby framework due to the extensive knowledge base available for it and the availability of more resources. Besides, it is fast, simple and efficient.

Step 1: Set up Sinatra

  • Install RVM and Ruby
\curl -sSL https://get.rvm.io | bash -s stable --ruby
  • Next, install bundler and Sinatra using RubyGems
gem install bundler
gem install sinatra

Step 2: Create a Gemfile

  • Create a file named Gemfile with the following contents in your project directory. You can also use and IDE for creating a new project.
source ‘https://rubygems.org'gem ‘sinatra’, ‘~> 2.0’

Step 3: Install Dependencies

  • Run the following commands to install the dependencies:
bundle install

This command will generate a file named Gemfile.lock.

Now that we have set up and installed Sinatra we need a database to be able to actually store all of the data. In our tutorial, we’ll use Mongo. MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with a schema.

Step 4: Install MongoDB and set it up

Object Relational Mappers (ORMs) are used to connect to databases from an application. In the case of Sinatra, we will be using Mongoid ORM. But before that, let us set up MongoDB in your system.

  • To install mongo in Ubuntu type the following commands:
sudo apt-key adv — keyserver hkp://keyserver.ubuntu.com:80 — recv 7F0CEB10echo ‘deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen’ | sudo tee /etc/apt/sources.list.d/mongodb.listsudo apt-get updatesudo apt-get install -y mongodb-orgTo install in Sinatra, go to the Gemfile that you created earlier and add the following line:gem 'mongoid', '~> 7.0'
  • Run bundle install again to install the dependencies.

Step 5: Run MongoDB Locally

Start the MongoDB server first

sudo service mongod start

Now that MongoDB is installed and running, create a file named config/mongoid.yml in your current project with the following content

development:
clients:
default:
database: blog_development
hosts:
- localhost:27017
options:
server_selection_timeout: 1

Step 6: Create a Basic Application

Lets now get to actually creating the application. Let's think of a simple blog application.

  • Create a file named app.rb with the following contents:
require 'sinatra'
require 'mongoid'
  • Load the Mongoid configuration file and configure Mongoid. This is done automatically when Mongoid is used with Rails, but since we are using Mongoid with Sinatra, we need to do this ourselves:
Mongoid.load!(File.join(File.dirname(__FILE__), 'config', 'mongoid.yml'))

Now that we have a Mongo Connection, we can define the models which are nothing but the way in which our data will be stored in the DB

class Post
include Mongoid::Document

field :title, type: String
field :body, type: String

has_many :comments
end

class Comment
include Mongoid::Document

field :name, type: String
field :message, type: String

belongs_to :post
end

To access these models, we will be defining some routes

  • Read all the posts
get '/posts' do
Post.all.to_json
end
  • Create a new post
post '/posts' do
post = Post.create!(params[:post])
post.to_json
end
  • Read a single post in detail with all the comments
get '/posts/:post_id' do |post_id|
post = Post.find(post_id)
post.attributes.merge(
comments: post.comments,
).to_json
end
  • Create a new comment on a post
post '/posts/:post_id/comments' do |post_id|
post = Post.find(post_id)
comment = post.comments.create!(params[:comment])
{}.to_json
end

Step 7: Running the Application

Once all this is done, let us run the application

bundle exec ruby app.rb

Step 8: Testing the API

You can use curl commands to test the API that you just created above.

curl http://localhost:3000/posts
# => []

curl -d 'post[title]=hello&post[body]=hello+world' http://localhost:3000/posts
# => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"}

curl http://localhost:3000/posts
# => [{"_id":{"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"}]

curl -d 'comment[name]=David&comment[message]=I+like' http://localhost:3000/posts/5d8151ec96fb4f0ed5a7a03f/comments
# => {}

curl http://localhost:3000/posts/5d8151ec96fb4f0ed5a7a03f
# => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"title":"hello","body":"hello world","comments":[{"_id":{"$oid":"5d8157ac96fb4f20c5e45c4d"},"message":"I like","name":"David","post_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"}}

--

--