skip to Main Content

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


  1. Chosen as BEST ANSWER

    Use json instead of params

    response = requests.post(url, json=query_params, headers=headers)
    

    This worked!


  2. 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())
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search