简体   繁体   中英

Ruby on Rails: Trying to make multiple API requests based on an array of values. How can I insert these values as parameters into the API URL?

I'm using rest-client (2.1.0-x64-mingw32) with Ruby on Rails (v6.0.3.2).

I'm trying to make multiple API requests based on an array of values.

For example, here is a short array containing the values to be inserted in the API URL as parameters:

array = ["DUBLIN%20CITY%20COUNCIL", "SOUTH%20DUBLIN%20COUNTY%20COUNCIL"]

I will then use a loop to insert these into each request resulting in the following:

https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=DUBLIN%20CITY%20COUNCIL&CategorySelected=OFFICE&Format=json&Download=false

https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=SOUTH%20DUBLIN%20COUNTY%20COUNCIL&CategorySelected=OFFICE&Format=json&Download=false

First, to try inserting a single value, I have tried this:

require 'rest-client'
require 'json'

localAuthority = "DUBLIN%20CITY%20COUNCIL"

response = RestClient.get('https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=#{localAuthority}&CategorySelected=OFFICE&Format=json&Download=false')
json = JSON.parse(response)

However, this is resulting in the following error:

rails aborted!
URI::InvalidURIError: bad URI(is not URI?): "https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=\#{localAuthority}&CategorySelected=FUEL/DEPOT&Format=json&Download=false"

The value doesn't seem to be passing correctly into the URL. How can I insert these values as parameters into the API URL?

Take a closer look at the error. The URL in the error message contains the string

...#{localAuthority}...

The interpolation didn't work because ruby only supports #{} syntax within double quoted strings.

Try and replace your single quotes with double quotes (")

"...#{localAuthority}..."

I'll spare you the lecture on sanitizing inputs but, please, pay attention to where you get these strings from and make sure to properly escape them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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