DEV Community

Hope Pete
Hope Pete

Posted on • Updated on

Building a web basic API with Sinatra and Active Record to support a React Front-End

Image description

What is Sinatra?

Sinatra is a minimal web framework created to give users the core essentials and abstractions needed to create straightforward and dynamic Ruby web applications. Prior to developing Sinatra applications, it is crucial to have a fundamental understanding of the Ruby programming language.

Image description

CRUD Operations

The Front-End component uses Active-Record to interact with the database and API routes built with Sinatra handle several different CRUD actions:

  1. Creating a new to do

  2. Reading a to do

  3. Updating a to do

  4. Deleting a to do

Basic Active Record migrations setup:

  • Create the app/models directory. Here is where your application controller file and database models will be located.

  • Create models. File names should be lowercase (for example, task.rb). Class names should be singular and with the first letter capitalized. For example, class Task

  • Create new migration files with the following command (replace create_models with a name of your choosing, and make sure _models is plural): bundle exec rake db:create_migration NAME=create_models

  • table names should be lower case, and plural versions of their corresponding models. For example, model name = task, and table name = tasks

  • Run migrations with the following command: bundle exec rake db:migrate .After migrations complete, check your schema.rb file.

  • In db/migrate folder in seeds.rb file, fill out seed data. Ruby Faker Gem might be useful. Using and run the following code to populate your database with dummy data. bundle exec rake db:seed

  • Run bundle exec rake console to view and manipulate data from your database

In Conclusion, With Active Record and Sinatra, a straightforward API can be easily created. Because so much complexity has been abstracted away by these Ruby Gems, getting started requires very little code.

Discussion (0)