我如何在请求中使用HTTParty传递变量?

问题描述 投票:0回答:2

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

是否可以在请求获取或删除的def retrieve方法中直接传递变量的值?I want to use the same value generated in the var that stores the faker gem and pass both get and 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
ruby httparty
2个回答
0
投票

来吧,编译时只有一个问题。 “ {”错误“:{”文本“:SQLSTATE [23000]:违反完整性约束:1048列'employee_name'不能为空}}”“

我相信一定是因为JSON输出。在前面的带有JSON的代码中,输出有效!我需要在您的代码中调整JSON输出。


0
投票

只需解析API的响应并使用获取的ID。创建员工时不需要传递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)

请阅读红宝石中的变量-局部变量,实例变量和全局变量之间有什么区别。全局变量应在极少数情况下使用,更多时候需要实例/局部变量。

© www.soinside.com 2019 - 2024. All rights reserved.