DEV Community

valera2022
valera2022

Posted on

How Does A Sinatra API Looks Like In Ruby?

Sinatra offers us a way to build Routes for Our Front-end and back-end to connect with each other.

First Let us explain some basic terms before we divide into details.

What is MVC?

It stands for Model View Controller.
The view will be the Browser where the user sends some requests to the back-end. These requests are handled by the middle man which is the controller(aka Sinatra in our case). Our controller then request the Model(Ruby with Active record in our case) to view/change the data.

What is Active Record?

"Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system."

What is Sinatra?

"Sinatra is a small web framework that provides a Domain Specific Language (or DSL) implemented in Ruby. Blake Mizerany created it and provides a lightweight option for developing simple web applications. Sinatra is Rack-based, which means it uses Rack under the hood and can use many tools designed to work with Rack. It's been used by companies such as Apple, BBC, GitHub, LinkedIn, and more."

What is an API?

API stands for Application Programming Interface.
An API allows you to access resources from Your own backend or Other people's Data. API can Make the programmer’s life easier since we could use resources from other’s people/companies and implement them in our code.

Let us talk about Modules

as we defined before Module/s have the responsibility for changing or viewing the data.

In Ruby, we make classes that are modules of data tables.

class Supervisor < ActiveRecord::Base
    has_many :workers
    def destroy_all
        Doctor.destroy_all
  end


end
Enter fullscreen mode Exit fullscreen mode
class Worker < ActiveRecord::Base
    belongs_to :supervisor
    def destroy_all
          Patient.destroy_all
    end


end

Enter fullscreen mode Exit fullscreen mode

These modules are related to one another through the keywords has many and belongs to.

Sinatra is gonna interact with modules and the modules will handle the data.

Let us talk about Sinatra

Sinatra’s syntax is as follows:

get  “/workers” do
  workers = Worker.all
  workers.to_json()
end
Enter fullscreen mode Exit fullscreen mode

We start with an HTTP verb. “/workers” will be our URL. This is how Sinatra handles each different HTTP request So If I send a get request from the browser or my front-end The Ruby inside this specific Route will come into action.

RESTful Routes

REST stands for Representational State Transfer which provides a way of mapping HTTP verbs (get, post, put, delete) and CRUD actions (create, read, update, delete) together. It is a convention for defining routes and when something follows the rest principle it is known as RESTFUL.

So It is convection for Our Routes.
Let’s say we want to Send a Get request, my Route will be named in this matter:

So It is convection for Our Routes.
Let’s say we want to Send a Get request, my Route will be named in this matter:

  get  “/workers” do
      workers = Worker.all
      workers.to_json()
  end
Enter fullscreen mode Exit fullscreen mode

This is an Index Route meaning it is not one single Item but a List of all the workers.

Or A POST request:

post '/workers' do
    supervisor = Supervisor.find_by(id: params[:supervisor_id] )
    worker = doctor.workers.create(
      name: params[:name],
      dob: params[:dob],
      doh: params[:doh],
      ins: params[:ins],
      sick_days: params[:sick_days],
      security_level: params[:security_level],
      vacation: params[:vacation],
      pay: params[:pay],
      note: params[:note]

    )
patient.to_json

end
Enter fullscreen mode Exit fullscreen mode

This is the create Route.

How About A Patch?

patch  “/workers/:id” do
      worker = Worker.find(params[:id])
      worker.update(
          name: params[:name]
)
      workers.to_json()
end
Enter fullscreen mode Exit fullscreen mode

This is the Update Route.

If we wanted to delete one of them, we will send a delete request we will “catch it” with something like :

delete '/workers/:id' do 
    worker = Worker.find(params[:id])

    worker.destroy()


  end 
Enter fullscreen mode Exit fullscreen mode

This is the Destroy Route.

**

Common mistakes and debugging tips.

**

You can check if your API ends are working by putting a binding.pry in it and see If a request may to it triggers binding.pry( you can use Postman if you don’t have the corresponding fetch on the front-end).

post '/workers' do
    supervisor = Supervisor.find_by(id: params[:supervisor_id] )
    worker = doctor.workers.create(
      name: params[:name],
      dob: params[:dob],
      doh: params[:doh],
      ins: params[:ins],
      sick_days: params[:sick_days],
      security_level: params[:security_level],
      vacation: params[:vacation],
      pay: params[:pay],
      note: params[:note]



    )
    worker.to_json
    binding.pry

end
Enter fullscreen mode Exit fullscreen mode

If it does not open the pry console on the back end, check if there are any issues with your front-end request.

Another Silly thing that could mess up your response from the server is that last line .to_json . Make sure this statement is in there.

To recap:
Sinatra works as a middle between the View aka the Browser and the Module/s.
The module (ruby with active record) view or change data in the data base and send the response back.

Resources:

https://www.geeksforgeeks.org/restful-routes-in-node-js/
https://guides.rubyonrails.org/active_record_basics.html
https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces

Top comments (0)