Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests - pass parameter via GET [closed]

I am trying to call an API and pass some parameters to it.

My endpoint should look like:

https://example.com?q=food food is the parameter

import requests
parametervalue = "food"
r = requests.get("https://example.com/q=", parametervalue)

When I do print r.url, I do not get the correct result - the value is not passed.

Updated:

Error:

  r = requests.get('https://example.com', params={'1':parametervalue})
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get
  return request('get', url, **kwargs)

Update:

Answer posted below. Thank you.

Note: The SSL error mentioned in the post was due to me running Python 2.7. I used python3 and it fixed the issue.

like image 539
Cody Raspien Avatar asked Jun 07 '18 09:06

Cody Raspien


People also ask

How do you pass a query parameter in GET request Python?

To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request. then https://somewebsite.com/?param1=value1&param2=value2 would be our final url.

Can we pass parameters in GET request?

get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.

How do you send a patch request in Python?

How to make Patch request through Python Requests. Python's requests module provides in-built method called patch() for making a PATCH request to a specified URI.


1 Answers

Here's the relevant code to perform a GET http call from the official documentation

import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)

In order to adapt it to your specific request:

import requests
payload = {'q': 'food'}
r = requests.get('http://httpbin.org/get', params=payload)
print (r.text)

Here's the obtained result if I run the 2nd example:

python request_test.py
{"args":{"q":"food"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.1"},"origin":"x.y.z.a","url":"http://httpbin.org/get?q=food"}
like image 78
Pitto Avatar answered Sep 30 '22 15:09

Pitto