如何从外部API接收POST的内容

时间:2013-06-25 01:39:45

标签: ruby-on-rails api post

Houdini API发送如下所示的回发:

{
  "api_key": "keykeykeykeykey",
  "environment": "production",
  "postback_url": "http://example.com/postbacks",
  "blueprint": "research_link_data",
  "input": {
    "name": "example name"
    "website": "example website"
  }
  "status": "processing",
  "output": {
    "Correction": "example Correction"
    "has_book": "example has_book"
    "search_results_link": "example search_results_link"
  }
}

(使用真正的API_Key。)

(您在向API发送初始请求时自行设置postback_url。)

为了接收和处理这些回发,我有:

class Postback < ActiveRecord::Base
  attr_accessible :uuid
  belongs_to :survey
  extend FriendlyId
  friendly_id :uuid
  after_create :generate_uuid
  def generate_uuid
    self.update_attributes :uuid => SecureRandom.uuid
  end
end

class PostbacksController < ApplicationController
  respond_to :html
  def receive
    @postback = Postback.find(params[:id])
  end
end

Testivate::Application.routes.draw do
  resources :postbacks, :only => [:index, :show] do
    member do
      post :receive
    end
  end
end

Simple REST Client中,我有:

  1. 选择了POST单选按钮
  2. 输入“http etc postbacks / 32e5a1bb-452f-4ad2-9a42-c17239f3d964 / receive作为URL(这是一个真正的UUID,抱歉StackOverflow不允许我发布完整的本地URL)
  3. 将Header字段留空(因为我不知道该放什么)
  4. 将以下内容放入数据字段:

    {“api_key”:“keykeykeykeykey”,  “环境”:“生产”,  “postback_url”:网址,  “blueprint”:“research_link_data”, “输入”:{   “名称”:“示例名称”   “网站”:“示例网站”}   “状态”:“处理”,   “输出”:{     “更正”:“示例更正”     “has_book”:“示例has_book”     “search_results_link”:“example search_results_link”}}

  5. (该URL与我在上面第2步中列出的相同.StackOverflow不喜欢指向本地服务器的URL抱歉。抱歉,我无法让StackOverflow将其格式化为代码块。)

    然后我使用Pry进入postbacks#receive行动。为什么我只看到:

    > params
    => {"action"=>"receive",
     "controller"=>"postbacks",
     "id"=>"32e5a1bb-452f-4ad2-9a42-c17239f3d964"}
    

    我如何获得其他结果?

    谢谢,

    史蒂芬。

2 个答案:

答案 0 :(得分:0)

tutorial on simple-rest-client表示您必须设置标题字段才能使表单发布工作:

“添加内容类型:application / x-www-form-urlencoded到标题”

答案 1 :(得分:0)

答案是:

  1. 确保控制器响应JSON(respond_to :html, :json
  2. 插入我试图接收的示例JSON中缺少的一些逗号
  3. 将POST标头设置为Content-Type: application/json Accept: application/json