Creating An API
A step-by-step tutorial of how to create an API in rails so users can access the data you want to provide. In this example, I will populate a postgreSQL database with randomly generated book information using faker gem, then give users the ability to create, read, update, and delete entries. To start your api, go to terminal and type:
rails new books-api --database=postgresql
cd books-api/ to get to the api folder you’ve just created and make your database by typing
rails g model Book title author genre tells the API the the attributes of “Book” will be title, author, and genre. All of which will be input as strings, the default value. Open your api folder and check your migration file.
Go to you gemfile and add
gem 'faker' to help us generate random book info to fill the database.
In your seed file, put the following:
title = Faker::Book.title,
author = Faker::Book.author,
genre = Faker::Book.genre
This will create 100 instances of Book with the given attributes. After confirming everything is correct, type
rake db:seed in your terminal.
rails g controller books to create your controller (if you plan on creating multiple versions of your api, you can save time by using
rails g controller api/v1/books instead, which I will do here).
open up routes.rb and set up your routes:
get '/' => 'books#index'
namespace :api do
namespace :v1 do
get ‘/books’ => ‘books#index’
post ‘/books’ => ‘books#create’
get ‘/books/:id’ => ‘books#show’
patch ‘/books/:id’ => ‘books#update’
delete ‘/books/:id’ => ‘books#destroy’
Your books controller should end up looking the same as a normal CRUD app without methods for ‘new’ or ‘edit’ since everything will be done through REST requests.
In order to display our data, we need to create views to show all book data as well as individual books. By creating a partial, we can eliminate some repetition. In your book view folder, create a file called _partial.json.jbuilder This will use the jbuilder gem that automatically loads in your gemfile when you make a new rails app. It’s important to have the underscore at the beginning so it will be recognized as a partial.
add the following inside the file:
in the same folder, create a file called index.json.jbuilder and add:
json.array! @books, partial: ‘book’, as: :book
in the same folder, create a file called show.json.jbuilder and add:
json.partial! @book, partial: ‘book’, as: :book
in your applications_controller.rb you’ll need to change
with: :exception to
you can now access your data by going to localhost:3000/api/v1/books.json or localhost:3000/api/v1/2.json (2 can be replaced with any id that relates to an instance in your database). You can change the data using postman or another rest client by adding a header with the key “Accept” with a value of “application/json”.