Reputation: 1963
To filter the output, I can send a JSON to the API, like :
curl -X GET https://api.mysite.com/user \
-H "Authorization: XXXXX" \
-H "Content-Type: application/json"
-d '{
"q": {
"name": {
"eq": "0aslam0"
}
}
}'
The above works just fine. I am trying to send the same via python code using requests
library.I tried the following code:
r = requests.get(url, headers=my_headers, params=payload)
where
url = "https://api.mysite.com/user"
my_headers = {
'Authorization': 'XXXXX',
'Content-Type': 'application/json',
'Accept': 'application/json',
}
data = {
"q": {
"name": {
"eq": "0aslam0"
}
}
}
payload = json.dumps(data)
but r.text
contains the output of a normal GET without applying filter. I logged the request, and saw that I was getting a redirect 301
. I don't understand my mistake.
EDIT 1
I changed the code to :
r = requests.get(url, headers=my_headers, json=payload)
@Martijn was right. Using params
was wrong. But the above also didn't succeed. I also added a header 'User-Agent': 'curl/7.40.0'
, to see if that could work. No luck there as well.
EDIT 2
The API documentation says, filtering can be done by another method. Changing the url into:
GET /user?q%5Bname%5D%5Beq%5D=0aslam0 HTTP/1.1
It is HTML encoded. So I tried, to format my url into such a format and avoid sending the payload, like:
r = requests.get(url, headers=my_headers)
And it works! So at least now I have a solution to my problem. But the question on how to send the payload (the method discussed above) for a GET request, still remains.
Upvotes: 2
Views: 31621
Reputation: 1121148
When you use -d
, the data is sent as a request body. params
sends a URL query string, so that's the wrong argument to use.
Note that packaging along a request body with a GET
method is technically a violation of the HTTP RFCs.
You'd have to send your request the data
argument set instead, or pass in your dictionary to the json
keyword argument and requests
will encode that and set the right Content-Type
header for you:
my_headers = {
'Authorization': 'XXXXX',
}
data = {
"q": {
"name": {
"eq": "0aslam0"
}
}
}
r = requests.get(url, headers=my_headers, json=data)
Upvotes: 5