I want to pass a json query as an argument in the requests.get method in python and get the query based response from the url.
query_params = {
"query": {
"exists": {
"field": "user_id"
}
},
"size":10000
}
headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
response = requests.post(url, params=json.dumps(query_params), headers=headers)
print(response.json())
Here the output is not based on the query parameters, it is the normal response we get even if we don’t pass the query.
I tried the get method
response = requests.get(url, params=query_params, headers=headers)
Both gave me a response that is not based on the passed query. I have also tried the same query in postman that gives me the correct response. I ensured that the headers are the same in both postman and in my script. The header format is X-API-Key:.
What is the correct way to pass a query request in the requests library to get a query based response?
>Solution :
To pass a JSON query as an argument in the requests.get() method in Python, you need to use the json parameter instead of the params parameter. The params parameter is used to pass query parameters in the URL, while the json parameter is used to send JSON data in the request body.
import requests
import json
query_params = {
"query": {
"exists": {
"field": "user_id"
}
},
"size": 10000
}
headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
response = requests.get(url, json=query_params, headers=headers)
print(response.json())