How to return multiple parameters from a Ruby Api name with Faraday

Asked

Viewed 32 times

0

Hello, I have a question of how to return multiple parameters of an attribute in an api. I’ve tried concatenating using | and %df but could not. It only accepts a name and prints correctly, when I do a gets.chomp with two names, it doesn’t work.

  def self.frequencia_decadas
    puts 'Digite o nome para obter a frequencia por décadas'
    nome = gets.chomp
    response = Faraday.get("https://servicodados.ibge.gov.br/api/v2/censos/nomes/#{nome}")
    json = JSON.parse(response.body, symbolize_names: true)
    json.map do |decadas|
    @decadas = decadas[:res].map do |frequencia|
    @frequencia = nome, frequencia[:frequencia], frequencia[:periodo]
    end
    end
  end

1 answer

1

Look, the problem is not only the ruby code, but the API itself.

this API accepts more than one name separated by |

https://servicodados.ibge.gov.br/api/v2/censos/nomes/fernando|maria

in this case, you need to encode the character | that in HTML would be %7C

Voce can learn more about encoding here https://www.w3schools.com/tags/ref_urlencode.ASP

but you can count on URI.encode to find sweat Uris

here is an example

require 'faraday'
require 'json'
require 'pry-nav'

def teste
  nomes = []
  loop do
    puts 'Digite o nome para obter a frequencia por décadas (pressione enter para finalizar)'
    nome = gets.chomp

    break if nome == ""
    nomes << nome
  end

  busca = nomes.join("|")
  uri = "https://servicodados.ibge.gov.br/api/v2/censos/nomes/#{busca}"
  final_uri = URI.encode(uri)

  response = Faraday.get(final_uri)
  json = JSON.parse(response.body, symbolize_names: true)
  puts json.map { |entry| entry[:nome] }
end

teste

Browser other questions tagged

You are not signed in. Login or sign up in order to post.