Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

LESSON: rails-api-single-resource



By the end of this, developers should be able to:

  • Follow along in the creation of an API.
  • Build a complete server side API in Rails
  • Create a model with full CRUD capability


Error-driven development: Using error messages to drive next development task. See an error, learn what error to expect. Embrace the errors, and they will tell you what your next task is.


  • We are creating an API to work with a single resource, in this case a Library API.

  • This lesson's readme is here, but the actual commits and Rails app is located on the campus server here

  • We will set up CRUD operations for the library.

  • All user stories are on the campus server repo here

  • Version 1

    • As a user, I want to view a single book
    • As a user, I want to view all books
    • As a user, I want to create a book with a title and author
    • As a user, I want to edit a book's title and author
    • As a user, I want to delete a book
  • ERD (just version 1) Library ERD diagram

Database and Rails

  • Rails uses ActiveRecord to connect your Postgresql database to your Rails application
  • To update your Postgresql database structure, you use a Rails migration
  • To add data to your database, you can use the Rails console, curl scripts or some other client that accesses your Rails API

Think of a database as a neighborhood - without any tables, it's just an empty plot of land - you add structure by adding Tables to a database, these are like houses in a neighborhood - But it's not yet populated yet! There's no data in the tables. - When you add data, it's like people moving into the houses

In Rails, the empty database is created by bin/rails db:create - This will create the database, which you can verify by looking at your databases in the psql console

In Rails, adding tables and structure is done by a 2 step process using a migration: - Step 1 is generating a migration file: - A new migration file is generated with bin/rails generate migration <MigrationName>. You can add additional command line arguments to auto-fill in the migration, like AddColumnToTable column_name:data_type - Step 2 is running the migration, which applies the changes to your database - bin/rails db:migrate

CRUD in Rails:

Index Action (HTTP GET / Read)
  • Tips:
    • Separate responsibilities, use the MVC pattern to get our request to the appropriate place in the application, and return the appropriate data to the client (remember the Acting out MVC exercise)

    • Use Error Driven Development

    • Walkthrough here

    • Start with curl script. Does it work? Where do we start writing application code to make it work (what is the "entry point" of the request?)

    • Step 0: Define feature

      • User story:
        • As a user, when I visit localhost:4741/books, I should get back all books
      • curl request
        • curl --include --request GET "http://localhost:4741/books" \
    • Step 1: Route

      • Does localhost:4741/books "work"? Why or why not?
       	get '/books', to: 'books#index'
      • shorthand
       	resources :books, only: [:index]
      • This tells Rails, "When you receive a GET request at the URL path /books, invoke the index method specified in the BooksController class."
    • Controller

      • Visit https://localhost:4741/books now. Great success? Use the error to drive the next development task, creating a controller to handle the request.
      • To spin up a new controller, we can just run bin/rails generate controller books
         class BooksController < ApplicationController
         	# methods go here
         	# controller methods are usually just the CRUD actions: index, show, create, update, destroy
         	def index
       	  @books = Book.all
       	  render json: @books
    • Model

      • Why does Book.all succeed or fail? The ORM must know that calling the class method .all on Book. If it fails, then we must look at the model (does it exist? is it named correctly?)
      • Generate a model by: bin/rails generate model Book title:string author:string
        • This generates a new model in app/models named book.rb. The generator also gives us a few other files: a migration that creates our database table calls books, with columns title (data type string or text, depending on db driver), and author (also data type string / text)
Show Action (HTTP GET / Read)
Delete Action (HTTP DELETE / Destroy)
Update Action (HTTP PATCH / Update)
Create Action (HTTP POST / Create)