繁体   English   中英

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

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

我对Rails中的API相当陌生,因此我将需要一些帮助来解决我面临的问题。

我只想通过我的应用程序发出的POST请求在API数据库上创建一条记录。

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

因此,这是我到目前为止所做的:

对于将使用API​​的应用程序,我正在使用HTTParty gem

我尝试使用以下代码在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' })

这是我的用于创建图书的图书控制器

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

但是当我创建书籍时,它仍然不会通过发布请求在API的数据库上创建这些书籍。

请任何形式的协助将不胜感激。 谢谢。

在执行请求时检查您的日志,但我怀疑您需要将身体更改为:

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

请注意,顶部的book钥匙是不同的。

在@ paulo-fidalgo和@tejasbubane的贡献之后,我找到了解决该问题的可行方法。

这是更正后的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'
  }
)

就这样

我希望这有帮助。

暂无
暂无

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

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