Creating a Rails api easy version!!
Today I am going to walk you through the incredibly simple process of creating an api using Ruby on Rails. Of course you are going to need to have Ruby on Rails installed on your computer, so if you don’t already go ahead and get it downloaded… it may take a sec... If you already have Rails on your computer go ahead and open up a terminal and cd into the folder you want your new project to live.
kealohaabe@kealohas-mbp code % cd Projects
The next step is to create the Rails api! Its very simple. In this case I’m going to create the backend for a cigar lover app.
kealohaabe@kealohas-mbp Projects % rails new cigar_api --api
As you can see in the command line you need to write rails new name_of_app — api. This is going to take a bit of time and you will see your api being built! Once the build is finished the next step is to cd into the new file. I like to open it with VS code so for me the next command is…
kealohaabe@kealohas-mbp Projects % code cigar_api
Now we are in VS code its time to use scaffold
kealohaabe@kealohas-mbp cigar_api % rails g scaffold Cigar brand:string line:string country:string size:string about:text
So as you can see here in the command line you call rails g (or generate) scaffold, the name of your Class and the migration tables for creating the schema.
After the scaffolding is finished go ahead and check in the app/controllers folder to see the magic of scaffold! If all is good the next step is to migrate.
kealohaabe@kealohas-mbp cigar_api % rails db:migrate
Now check your schema and make sure everything is good. If so make some seed data if you want. To do this open up your db folder and go into seeds.rb
Cigar.create(brand: "Monte Cristo", line: "White", country: "Dominican Republic", size: "Robusto", about: "One of the most well know cigars. The go to for celebrations of any kind!")Cigar.create(brand: "Romeo y Julietta", line: "Reserva Real", country: "Dominican Republic", size: "Church Hill", about: "Ole faithul. A classic that never lets you down")
Use the create method to create new objects. When you are finished with the seed data go ahead and enter in the command line…
kealohaabe@kealohas-mbp cigar_api % rails db:seed
Now you are almost able to see your api up and running in your chrome browser at localhost:3000. To do this of course you will have to run the rails app first. In the terminal write …
kealohaabe@kealohas-mbp cigar_api % rails s
Now it should be up and running !! Go check it out in your browser at
http://localhost:3000/cigars
We have just created a working api! Rails is incredibly powerful and makes our lives as developers much easier! Thank you for reading and I hope this was a little help!