0

I'm fairly new to API in Rails, and so I will need some assistance for the issue that I am facing.

All I want is to create a record on the database of the API through a POST request from my application.

That is to create a record on both databases (my database and the on the database of the API through a POST request from my application) whenever I create a book.

So this is what I've done so far:

For the app that will consume the API I am using the HTTParty gem.

I have tried to implement in my create action of the Books Controller using the code below:

 @result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register', 
          :body => {  :name => '#{name}',
                      :author => '#{author}',
                      :description => '#{description}',
                      :category_id => '#{category_id}',
                      :sub_category_id => '#{sub_category_id}'}.to_json, 
          :headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })

Here is my Books Controller for creating books

require 'httparty'

class BooksController < ApplicationController
  include HTTParty

  before_action :set_book, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, except: %i[show index]
  skip_before_action :verify_authenticity_token

  # GET /books
  # GET /books.json
  def index
    @books = Book.search(params[:keywords]).paginate(:page => params[:page], :per_page => 9).order('created_at DESC')
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = Book.new
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end

    @result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register', 
      :body => {  :name => '#{name}',
                  :author => '#{author}',
                  :description => '#{description}',
                  :category_id => '#{category_id}',
                  :sub_category_id => '#{sub_category_id}'}.to_json, 
      :headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })

  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:name, :author, :description, :category_id, :sub_category_id)
    end
end

But it still doesn't create these books on the database of the API through the post request when I create books.

Please any form of assistance will be highly appreciated. Thank you.

3
  • Everything looks like it should work, except you have an extra space in your url. Commented Mar 26, 2019 at 17:44
  • Put a debugger and see what @result is after the post request. That might give you an idea what went wrong. Commented Mar 26, 2019 at 18:02
  • @tejasbubane, I am not very experienced to do that now. I don't know if it is the way I am calling the key values in the body of the post request that is causing the issues. Or do you have a better way in which this can be done? Commented Mar 26, 2019 at 18:17

2 Answers 2

1

Check you logs when you do the request, but I suspect you need to change your body to:

{
  :book => {  
    :name => '#{name}',
    :author => '#{author}',
    :description => '#{description}',
    :category_id => '#{category_id}',
    :sub_category_id => '#{sub_category_id}'
  }
}.to_json

Note that book key at the top is the difference.

Sign up to request clarification or add additional context in comments.

3 Comments

I still have some issues though, please The issue is that the HTTParty post request runs as shown on the logs, but it doesn't add the record(s) to the database of the API.
@PromisePreston maybe add another question and post the logs
I just added a new question and I also posted the logs. Here is s link to the question: stackoverflow.com/q/55377117/10907864 Please help me. Thank you.
0

Following contributions from @paulo-fidalgo and @tejasbubane, I found a working solution to the issue.

Here is the corrected HTTParty Post Request

@results = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
  :body => {    
            :name => "#{@book.name}",
            :author => "#{@book.author}",
            :description => "#{@book.description}",
            :category_id => "#{@book.category_id}",
            :sub_category_id => "#{@book.sub_category_id}"}.to_json, 
  :headers => { 
               'Content-Type' => 'application/json',
               'Authorization' => '77d22458349303990334xxxxxxxxxx'
  }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.