Skip to content

Instantly share code, notes, and snippets.

@withoutwax
Last active January 24, 2024 16:28
Show Gist options
  • Save withoutwax/741c6e3c9a004c1463cbf7a1a3b719f8 to your computer and use it in GitHub Desktop.
Save withoutwax/741c6e3c9a004c1463cbf7a1a3b719f8 to your computer and use it in GitHub Desktop.
Guide on how to create an API-Only Application with Ruby on Rails 5

Creating an API-Only Application with Ruby on Rails

01 - Create a new API-only Rails app

rails new ror-app-name --api

02 - Basic Scaffold

01 - Model

This step is for creating a very basic level of model for us to work in. If you know already, or wish to apply your own custom models with relationships you can skip this step.

  1. Create an User model
rails generate model User name:string
  1. Create a Post model - association with User
rails generate model Post title:string body:text user:belongs_to
  1. Migrate the models
rails db:migrate

02 - Creating a Dummy Data

Gemfile

group :development do
  gem 'faker'
end

Install gem

bundle install

db/seeds.rb

5.times do
  user = User.create({name: Faker::Name.name})
  user.posts.create({title: Faker::Book.title, body: Faker::Lorem.sentence})
end
rails db:seed

03 - Routes

Nesting the API routes config/routes.rb

namespace 'api' do
    namespace 'v1' do
      resources :posts
      resources :users
    end
  end

Create an api folder inside App/controllers folder. Then create v1 folder inside api folder which you created. Then create controllers. Note - You do not have to create the controllers with rails generate controllers. Create the controllers simply by creating a new file. controllers/api/v1/users_controller.rb

module Api
    module V1
        class UsersController < ApplicationController
        end
    end
end

controllers/api/v1/posts_controller.rb

module Api
    module V1
        class PostsController < ApplicationController
        end
    end
end

04 - Apply CRUD to controllers

controllers/api/v1/posts_controller.rb

module Api
  module V1
    class PostsController < ApplicationController

      def index
        @posts = Post.order('created_at DESC')
        render json: {status: 'SUCCESS', message: 'Loaded posts', data:@posts}, status: :ok
      end

      def show
        @post = Post.find(params[:id])
        render json: {status: 'SUCCESS', message: 'Loaded posts', data:@post}, status: :ok
      end

      def create
        @post = Post.new(post_params)

        if @post.save
          render json: {status: 'SUCCESS', message: 'Post is saved', data:@post}, status: :ok
        else
          render json: {status: 'Error', message: 'Post is not saved', data:@post.errors}, status: :unprocessable_entity
        end
      end

      def update
        @post = Post.find(params[:id])

        if @post.update_attributes(post_params)
          render json: {status: 'SUCCESS', message: 'Post is updated', data:@post}, status: :ok
        else
          render json: {status: 'Error', message: 'Post is not updated', data:@post.errors}, status: :unprocessable_entity
        end
      end

      def destroy
        @post = Post.find(params[:id])
        @post.destroy

        render json: {status: 'SUCCESS', message: 'Post successfully deleted', data:@post}, status: :ok
      end

      private
        def post_params
          params.permit(:title, :body)
        end

    end
  end
end

After updating the code, use software such as Postman to check whether all the routes are working properly.

@tur-ing
Copy link

tur-ing commented Jun 3, 2022

Very helpful, thank you!

@swapdefine
Copy link

it gives erorr undefined method post

@swapdefine
Copy link

it gives error undefined method post , I am using check screenshot is attached for reference
Screenshot 2022-08-08 at 1 50 20 PM
rails 7

@bpradana
Copy link

bpradana commented Dec 2, 2022

if it gives error undefined method post on seeding, your user model (app/models/user.rb) should look like this

class User < ApplicationRecord
  has_many :posts
end

@Bria222
Copy link

Bria222 commented Apr 2, 2023

Step 2: Enable CORS (Cross Origin Resource Sharing)

CORS allows others to access your API. To prevent unwanted access to your API, Rails automatically disables CORS. In the file explorer of your newly created Rails API, expand the following directories to open the cors.rb file.

config>initializers>cors.rb

So, Uncomment lines 8-16. On line 10, change the code (origins 'example.com') to (origins'*') as shown below:

in config>initializers>cors.rb

lines 8-16

Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'

resources '*',
  headers: :any,
  methods: [:get, :post, :put, :patch, :delete, :options, :head]

end
end

In the 'explorer' file, scroll down and open Gemfile. Uncomment line 26, gem 'rack-cors':

in Gemfile

gem 'rack-cors'

@dwerth
Copy link

dwerth commented Jul 11, 2023

Since user_id is required to create a post you'll need to include :user_id as a permitted parameter in controllers/api/v1/posts_controller.rb for testing.

def post_params
    params.permit(:title, :body, :user_id)
end

here's a json example to use in postman

{
    "title": "This is a title",
    "body": "Body of post",
    "user_id": 1
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment