How to build a request for an API

Hi, I'm trying to make a request to an API using what we saw on the "Convert Our Request to a Script" module of the last course. The API I'm trying to fetch data from, asks to provide the basic information to access the REST API in the "header part" of the request. The basic info they ask for is "Authentication" & "Accept" (to request JSON) If I use a Chrome extension such as Advanced Rest Client, I manage to get a 200 response with what I want (http://snag.gy/MKc5Q.jpg), however I'm having troubles in generating the script since I still don't understand how to provide the basic info in the header part (as oppossed to doing it as a query parameter in the URL) Is there any particular thing I'd need to do to adapt the "craigslist_scraper.rb" script to work for this case? So far, I've got something like: /// -------------------- /// require 'open-uri' authentication = 'user&password' request_url = "https://partner.ws.qa1.domain.com/postings?checkIn=20151001&checkOut=20151003&locId=509&room1=1,1,3&room2=2,0,3&room3=0,1,4&pos=HCL&rateDetails=all&contentDetails=all&include=taxesAndFees" # Prepare API request uri = URI.parse(request_url) #uri.query = URI.encode_www_form(params) # Submit request result = open(uri).read # Display results to screen puts result /// --------------- ///

Posted about 4 years ago by gus
Posted about 4 years ago by gus

thanks, I understand the params (such as checkIn, checkOut) are passed as query parameters in the URL. My question relates more on how to pass the "Authentication" & "Accept" variables in the "header" part of the request (this is how the API asks to pass this variables).

1
Posted about 4 years ago by Alex Yang

I'm not sure, but you should probably take a look at your API documentation for examples. You may also want to take a look at this cheat sheet: http://augustl.com/blog/2010/ruby_net_http_cheat_sheet/

1
Posted about 4 years ago by Alex Yang

You should try using the craigslist_scraper.rb script as a template. Every API may be slightly different, but perhaps try something like this:

require 'open-uri'

# Set API token and URL
url = "https://partner.ws.qa1.domain.com/postings"

# Specify request parameters
params = {
checkIn: "20151001",
checkOut: "20151003",
...
}

# Prepare API request
uri = URI.parse(url)
uri.query = URI.encode_www_form(params)

# Submit request
result = open(uri).read

# Display results to screen
puts result

1