Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How fetch a json query response from an api in python using requests library?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading