简体   繁体   English

Rails:使用Rails和HTTParty将JSON发布到API

[英]Rails: Post JSON to API Using Rails and HTTParty

I'm fairly new to API in Rails, and so I will need some assistance for the issue that I am facing. 我对Rails中的API相当陌生,因此我将需要一些帮助来解决我面临的问题。

All I want is to create a record on the database of the API through a POST request from my application. 我只想通过我的应用程序发出的POST请求在API数据库上创建一条记录。

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. 那就是每当我创建一本书时,都要在两个数据库(我的数据库和API的数据库上通过来自我的应用程序的POST请求)上创建一条记录。

So this is what I've done so far: 因此,这是我到目前为止所做的:

For the app that will consume the API I am using the HTTParty gem . 对于将使用API​​的应用程序,我正在使用HTTParty gem

I have tried to implement in my create action of the Books Controller using the code below: 我尝试使用以下代码在Books Controller的create动作中实现:

 @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. 但是当我创建书籍时,它仍然不会通过发布请求在API的数据库上创建这些书籍。

Please any form of assistance will be highly appreciated. 请任何形式的协助将不胜感激。 Thank you. 谢谢。

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. 请注意,顶部的book钥匙是不同的。

Following contributions from @paulo-fidalgo and @tejasbubane, I found a working solution to the issue. 在@ paulo-fidalgo和@tejasbubane的贡献之后,我找到了解决该问题的可行方法。

Here is the corrected HTTParty Post Request 这是更正后的HTTParty发布请求

@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'
  }
)

That's all 就这样

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM