Intro
Now that we have the environment setup, we can finally start building our API for the web application. This article will go through how to create a basic REST API for perform CRUD (Create, Read, Update, Delete) operations.
Start
Lets start by creating the home page. Generate files needed for the home page by typing:
rails g controller home_page index
Create the resources for an object called book.
rails g resource book title author:text description:text pages:integer published:date
Migrate the database
rake db:migrate
Notes:
If this is the first time you are seeing the above commands, here is what it is doing in a nutshell for our purposes. ‘g’ is short for generate, so in the commands above we are telling rails to generate things such as a controller or resource. The index part is just the page itself (index.html) where you can write HTML in and the controller allows for this page to interact with the server (to get information from the database). Generating the resource in this case allows us to add the routes (or URL paths) for getting information about the book. This book is then set represented by a title, author (in text format), description, number of pages (in integer format), and when it was published (in date format).
Routes
Let’s add the routes for the api we are making. In the config/routes.rb file, add the lines:
root 'home_page#index' namespace :api do resources :books end
The routes.rb file should look like this: https://gist.github.com/mt9304/82f7a0dca262749e14ebbd28e3b8bbaf
Controller
Now let’s replace the contents in the books controller in /app/controllers/books_controller.rb to be:
module Api class EventsController < ApplicationController def index render json: Book.all end end end
Now go into /app/controllers and create an folder called api, then move the books_controller under there. New path should be /app/controllers/api/books_controller.rb
Any API related controllers should now go in that folder.
Note:
Putting books under the :api namespace and api folder allows you to access the resource in the URL after /api. So in this case, it would be website.com/api/books. Making books a resource by writing “resources :book” allows users to access books through its RESTful URLs. Below are the following URLs you will be able to use to get data about the books. Since we have the index method in the controller and views for books, you should be able to visit that page (we haven’t added any book records in the database yet, so these URLs wouldn’t return anything right now).
GET /api/books(.:format) api/books#index
POST /api/books(.:format) api/books#create
GET /api/books/new(.:format) api/books#new
GET /api/books/:id/edit(.:format) api/books#edit
GET /api/books/:id(.:format) api/books#show
PATCH /api/books/:id(.:format) api/books#update
PUT /api/books/:id(.:format) api/books#update
DELETE /api/books/:id(.:format)
More information on REST here: https://www.restapitutorial.com/lessons/restfulresourcenaming.html
Here are the basics that you need to know in Rails regarding these APIs and routes:
– Controllers will have a few standard methods:
index method for showing all the books (/books)
create method for creating a new book (/books/new)
show method for showing one particular book (/books/id where id is the book’s id in the database)
update method for updating an existing book (/books/id/edit)
destroy method for deleting an existing book (/books/id/ but with a DELETE method)
Here we will fill out the rest of the controller methods to allow for the above behavior through the API. Change your books controller so that it is: https://gist.github.com/mt9304/bd76031fe933b833beffd29e9af538dc
Adding Books
Now let’s add some Books to our database so that we can test out the API. Go into the Rails console by typing in the terminal:
rails c
(Make sure you are in the project’s folder)
The Rails console lets you run Ruby code in. real time to make changes to your application. In this case, we want to add a new Book, so let’s type in:
b = Book.create :title => "How To Cook", :author => "Bob", :description => "Teaches you how to cook. ", :pages => 20, :published => "2018-11-03" b2 = Book.create :title => "How To Bake", :author => "Bill", :description => "Teaches you how to bake. ", :pages => 15, :published => "2018-02-03"
Note:
While in the console, type “quit” to exit.
This will create 2 entries in our database in the Books table. The database right now is stored in /db/development.sqlite3. You can open this with sqlitebrowser.
If you haven’t downloaded it yet, you can install it by running these commands in the terminal:
sudo add-apt-repository ppa:linuxgndu/sqlitebrowser-testing sudo apt-get update && sudo apt-get install sqlitebrowser
Then you can go into your project folder and open it with the sqlitebrowser command:
sqlitebrowser db/development.sqlite3
You can right click the Books option and see your entries in there. Now you can try out the API urls above to see it in action (Make sure you start your server first by running: rails s). For example, go to localhost:3000/api/books/1
You should receive a page with information about one of the books we just created in JSON format. The “1” at the end of the URL represent’s the ID, which is found in the ID column of the Books table in the database. So if you go to localhost:3000/api/books/2 then it will give you information on the other book.
Navigation
The next article can be found here. Previous article is here.