Giter Club home page Giter Club logo

restful-api-ruby-on-rails's Introduction

Restful API Ruby on Rails

In this time I will create a simple Restful API with the Ruby on Rails framework.

Preparation

  • Use Postman for test your API
  • Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible.

Installation Ruby on Rails

Because we only create a simple Restful API, so what we run is the following command to create a project Ruby on Rails.

rails new project-name --api -T

This means that we will create a project only for the API without unit tests.

Configure

Activate Rack CORS on Rails to get our API. The easiest way to configure CORS on your Rails app is to use rack-cors gem. You can install it like any other gem, by executing:

gem install rack-cors

or by adding the following line into your Gemfile:

gem 'rack-cors'

Next, you need to provide the configuration for the gem. You need to inform Rails which origin it should allow. To do that, you need to create a new initializer for your application.

The content of the config/initializers/cors.rb should be the following:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "https://examples.com" ## or '*' if the API used is only for localhost.

    resource "*",
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Restful API as student example

create a model student with the attribute name, and address

rails generate model Student name: string address: text

create a students controller as follow

rails generate controller students

on the directory controller create a new directory as follows "api/v1" and move file student_controllers.rb to that directory. Next, change the command in the students_controller file to

module Api
  module V1
    class StudentsController < ApplicationController
      def index
        @students = Student.all
        render json: @students
      end

      def show
        @student = Student.find(params[:id])
        render json: @student
      end

      def create
        @student = Student.new(student_params)

        if @student.save
          render json: @student
        else
          render json: @student.errors, status: :unprocessable_entity
        end
      end

      def update
        @student = Student.find(params[:id])

        if @student.update(student_params)
          render json: @student
        else
          render json: @student, status: :unprocessable_entity
        end
      end

      def destroy
        @student = Student.find(params[:id])

        if @student.present?
          @student.destroy
          render json: @student
        else
          render json: { error: 'Student not found' }
        end
      end

      private
      def student_params
        params.require(:student).permit(:name, :address)
      end
    end
  end
end

Next, do API testing (GET, POST, PUT, DELETE) with Postman and check whether "localhost/api/v1/students" run well or not.

restful-api-ruby-on-rails's People

Contributors

myusuf20 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.