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?
3
Answers
Use json instead of params
This worked!
To pass a JSON query as an argument in the
requests.get()
method in Python, you need to use thejson
parameter instead of the params parameter. The params parameter is used to pass query parameters in the URL, while thejson
parameter is used to send JSON data in the request body.You can generate python code from your postman request.
I think it will solve your problem, also it will give you understanding of what you was doing wrong.
Here check this out Postman: Generating client code