Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass date arguments for requests.get command for API data?

I'm trying to get past weather data from API source. However I'm running into issues on how to pass the date arguments and specify dates I'm trying to get data for. I have been successful in using curl GET command, but not been successful in translating that over to requests.get command.

Here's what works:

curl -X GET -G "http://url.com/lat/long" -d start="2018-04-01" -d end="2018-04-04" --user abcd:1234

Using subprocess command I have gotten that code to work.Here's the code below:

cmd = 'curl -X GET -G "http://url.com/lat/long" -d start="2018-04-01"  -d end="2018-04-04" --user abcd:1234'

p = sp.Popen(cmd, shell=True,stdout=sp.PIPE, stderr=sp.STDOUT).stdout.read()

p.split('\n')[3]

Here's the code I have for requests.get:

r=requests.get("https://url.com/lat/long",auth=HTTPBasicAuth('user','password'))

However, cannot pass the date arguments through to limit my data pull to my specified date ranges.

Here's a couple of method's I have tried.

r=requests.get("https://url.com/lat/long",start=start,end=end,auth=HTTPBasicAuth('user','password'))

Also tried:

data = [
  ('startDate', '2018-04-01'),
  ('endDate', '2018-04-08'),
]

r=requests.get("https://url.com/lat/long",data=data,auth=HTTPBasicAuth('user','password'))

Can someone guide me in the right direction? I really want to stick with the request library command, but only thing thats working right now is running the curl command through the subprocess method, and I don't fully understand that process.

like image 334
pewpewpew Avatar asked Oct 12 '25 09:10

pewpewpew


1 Answers

Let's take a look at the G parameter in your curl command:

-G, --get           Put the post data in the URL and use GET

This means that your data will not be submitted in the body of the request, but in the url as a query string. With requests you can use the params argument to achieve that.

So your curl command is equivalent to:

import requests

url = 'https://url.com/lat/long'
data = {'start': '2018-04-01', 'end': '2018-04-08'}
creds = ('user','password')
r = requests.get(url, params=data, auth=creds)

print(r.text)
like image 132
t.m.adam Avatar answered Oct 15 '25 11:10

t.m.adam