首页 > 解决方案 > 如何通过 HTTParty 传递请求中的变量?

问题描述

我需要使用 Post 生成一个值并在查询中传递这个值并删除。这个怎么做?

def retrieve是否可以在request get或delete 的方法中直接传递变量的值?我想使用在存储伪造 gem 的 var 中生成的相同值,并同时传递 get 和 delete。

require 'HTTParty'
require 'httparty/request'
require 'httparty/response/headers'

class Crud    
  include HTTParty

  def create 
    @@codigo = Faker::Number.number(digits: 5)
    @nome    = Faker::Name.first_name
    @salario = Faker::Number.decimal(l_digits: 4, r_digits: 2)
    @idade   = Faker::Number.number(digits: 2)

    @base_url  = 'http://dummy.restapiexample.com/api/v1/create'

    @body = {
      "id":@@codigo,  
      "name":@nome,
      "salary":@salario,
      "age":@idade        
    }.to_json

    @headers = {
        "Accept": 'application/vnd.tasksmanager.v2',
        'Content-Type': 'application/json'
    }

    @@request = Crud.post(@base_url, body: @body, headers: @headers) 
 end

  def retrieve
    self.class.get('http://dummy.restapiexample.com/api/v1/employee/1') 
  end 
end

标签: rubyhttparty

解决方案


只需解析来自 API 的响应并使用获取的 id。创建员工时不需要传递id,它是自动生成的

class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def create 
    nome    = Faker::Name.first_name
    salario = Faker::Number.decimal(l_digits: 4, r_digits: 2)
    idade   = Faker::Number.number(digits: 2)
    #note, you should pass body as JSON string
    body = { name: nome, salary: salario, age: idade }.to_json

    headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: body, headers: headers) 
  end

  def retrieve(id)
    self.class.get("/employee/#{ id }")
  end 
end

> client = Crud.new 
> response = client.create
> id = JSON.parse(response)['id']
> client.retrieve(id)

请阅读 ruby​​ 中的变量 - 局部变量、实例变量和全局变量之间的区别。全局变量应该在极少数情况下使用,更多时候你需要实例/本地变量。


推荐阅读