Setting up an API with Rails

In this blog, we go over the steps for setting up a Rails based API.

installation
CORS
generate resource
create migration
add seed data
add actions to our controller
testing in Postman
some validations

1

run rails new this-is-a-blog –ap…


This content originally appeared on DEV Community and was authored by benjaminolmsted

In this blog, we go over the steps for setting up a Rails based API.

  1. installation
  2. CORS
  3. generate resource
  4. create migration
  5. add seed data
  6. add actions to our controller
  7. testing in Postman
  8. some validations

1

run rails new this-is-a-blog --api

This sets up the project for use as an API.

2

enable CORS (cross-origin resource sharing)
In the Gemfile, uncomment the gem 'rack-cors'
image

Then head over to config/initializers/cors.rb and uncomment lines 8-16 and change origins 'example.com' to origins '*' to allow requests from anywhere. If the API is meant to be consumed by a specific domain, put that domain here. For development purposes, '*' is fine.

image

bundle install

3

we generate our first resource with rails g resource Post

This generates a post.rb model, a posts_controller.rb controller, a CreatePosts migration, and adds a resources: posts to our routes.rb file.

4

we create our migration in db/migrate/{local_time}create_posts.rb

class CreatePosts < ActiveRecord::Migration[6.1]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.string :image_url
      t.timestamps
    end
  end
end

we could have had this step done automatically if we had run our generation like so: rails g resource Post title body image_url

and migrate with rails db:migrate

5

we add some seed data to db/seeds.rb

Post.create(title: "Editor Basics", body: "Use Markdown to write and format posts. You can use Liquid tags to add rich content such as Tweets, YouTube videos, etc.
    In addition to images for the post's content, you can also drag and drop a cover image")
Post.create(title: "Setting up an API with Rails", body:"First, run `rails new this-is-a-blog --api`") 
Post.create(title: "Writing a Great Post Title", body: "Think of your post title as a super short (but compelling!) description — like an overview of the actual post in one short sentence.
Use keywords where appropriate to help ensure people can find your post by search.")

and run rails db:seed

6

we head over to app/controllers/posts_controller.rb and lay out our actions

class PostsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found_response
rescue_from ActiveRecord::RecordInvalid, with: :record_invalid_response

    def index
        posts = Post.all
        render json: posts, status: :ok
    end

    def show
        post = find_post
        render json: post, status: :ok
    end

    def update
        post = find_post
        post.update!(post_params)
        render json: post, status: :accepted
    end

    def create
        post = Post.create!(post_params)
        render json: post, status: :created
    end

    def destroy
        post = find_post
        post.destroy
        head :no_content
    end

    private
    def find_post
        Post.find(params[:id])
    end

    def post_params
        params.permit [:title, :body, :image_url]
    end

    def record_not_found_response(e)
        render json: {error: e.to_s}, status: :not_found
    end

    def record_invalid_response(invalid)
        render json: {errors: invalid.record.errors.full_messages}, status: :unprocessable_entity
    end
end

7

now it's time to check our work using Postman

Fire up your server with rails s

image
Index is working!

image

Our Show route works!

image

So does the create route.

image

our patch updates.

image

Our delete deletes.
Our happy routes work! Excellent. Now let's check our error handling.

image

When we try to find an :id that does not exist, we get our helpful error!

Excellent! We made an API in rails.

8

now, let's put in some validations on our model.

class Post < ApplicationRecord
    validates :title, presence: true, length: {minimum: 2}
    validates :body, presence: true
end

Now let's see what happens if we try to post something without a body!
image

We cannot, thanks to the validations. We get that error thanks to our rescue_from ActiveRecord::RecordInvalid and our use of create! and update!, which will throw an ActiveRecord::RecordInvalid error if the request fails any validations.

The very basics of setting up an API in Rails, complete.

Resources:
https://guides.rubyonrails.org/active_record_validations.html

https://guides.rubyonrails.org/api_app.html

https://dev.to/lisahjung/beginner-s-guide-to-creating-an-api-from-scratch-using-rails-2eie


This content originally appeared on DEV Community and was authored by benjaminolmsted


Print Share Comment Cite Upload Translate Updates
APA

benjaminolmsted | Sciencx (2021-09-03T19:46:52+00:00) Setting up an API with Rails. Retrieved from https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/

MLA
" » Setting up an API with Rails." benjaminolmsted | Sciencx - Friday September 3, 2021, https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/
HARVARD
benjaminolmsted | Sciencx Friday September 3, 2021 » Setting up an API with Rails., viewed ,<https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/>
VANCOUVER
benjaminolmsted | Sciencx - » Setting up an API with Rails. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/
CHICAGO
" » Setting up an API with Rails." benjaminolmsted | Sciencx - Accessed . https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/
IEEE
" » Setting up an API with Rails." benjaminolmsted | Sciencx [Online]. Available: https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/. [Accessed: ]
rf:citation
» Setting up an API with Rails | benjaminolmsted | Sciencx | https://www.scien.cx/2021/09/03/setting-up-an-api-with-rails/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.